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()
Sheet1
Page 2
{
if (suspended)
{
suspended = false
notify()
}
}
//suspend needs to be created.
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.
}