I have written the following java applet code, mainly with the aim of suspending a thread instead of nullifying it and creating an another instance of it.
I want to know if the below written code is safe, or, in other way, good code to follow?
public class AppletThread extends Applet implements Runnable
{
Thread t;
volatile boolean suspendFlag;
Integer s = 0;
public void init()
{
t = new Thread (this, "AppletThread");
suspendFlag = false;
t.start();
}
public synchronized void start()
{
suspendFlag = false;
notifyAll();
}
public void run()
{
int i;
for (i = 0; i < 15; ++i)
{
repaint();
try {
Thread.sleep(1000);
} catch (InterruptedException e)
{}
++s;
synchronized (this)
{
System.out.println ("into synchronized(this)");
while (suspendFlag)
try {
wait();
} catch (InterruptedException e) { }
}
}
}
public synchronized void stop()
{
suspendFlag = true;
notifyAll();
}
public void destroy()
{
t = null;
}
public void paint (Graphics g)
{
g.drawString (s.toString(), 10, 10);
}
}
An another alternative i saw of starting and suspending(stopping, rather) was something like this. :
public void start()
{
stopFlag = false;
t = new Thread (this);
}
public void run()
{
while (true)
{
//code
if (stopFlag)
break;
}
}
public void stop()
{
stopFlag = true;
t = null;
}
here wait() is not used. Rather, the run() is simply ended using break.
Is this a better way than what i wrote above? I dont think so because here one creates a new instance every time the applet is started and stopped. Thats not the way in the former code; the same thread instance is being used.
Or is there another better alternative to both of this?
I hope to get a reply soon.. :)