CountingThread

CountingThread - public synchronized void suspend() {...

Info iconThis preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon
Sheet1 Page 1 import javax.swing.* import java.awt.* public class CountingThread implements Runnable { private int index private JLabel label private java.util.Timer timer private Thread thread = null private boolean suspended = false public CountingThread() { JFrame frame = new JFrame("Exercise") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setSize(400,100) Container cont = frame.getContentPane() index = 0 //index++ label = new JLabel("COUNT: " + String.valueOf(index)) label.setFont(new Font("TimesRoman", Font.PLAIN, 35)) cont.add(label) frame.setVisible(true) thread = new Thread(this) thread.start() } public synchronized void start() { if (suspended) { suspended = false notify() } } //This method needs to be overriden for applet public void start() { resume() } //since resume() and suspend() methods in Thread have been deprecated //we must create new methods for resuming and suspending threads. public synchronized void resume()
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Sheet1 Page 2 { if (suspended) { suspended = false notify() } } //suspend needs to be created.
Background image of page 2
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 4
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: public synchronized void suspend() { suspended = true } public void run() { while (true) { try { thread.sleep(1000) //waitForNotificationToResume2() } catch(InterruptedException ex) { System.out.println(ex) } index++ label.setText("COUNT: " + String.valueOf(index)) } } public synchronized void waitForNotificationToResume2() throws InterruptedException { while(suspended) wait() } //Note: when wait() is invoked, it pauses the thread and simultaneously //releases the lock.Causes current thread to wait until another thread //invokes the notify() method or the notifyAll() method for this object. //wait(), notify(), and notifyAll() must be called within a syncrinized method or block. //Otherwise IllegalMonitorStateException would occur. } Sheet1 Page 3 //resume method of this class since thread.resume() is deprecated Sheet1 Page 4 //Wakes up a single thread that is waiting on this object's monitor. //it throws InterruptedException...
View Full Document

Page1 / 4

CountingThread - public synchronized void suspend() {...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online