Reputation: 19
Please give me some vivid explanation in this regards. I have tried lots but i couldn't figured it out.
I'm completely messed up with the code segment of start method calling like recurrence in below program and even how start method called first time before entered into start method body.
Thanks in advance.
package appletexample;
import java.awt.*;
import java.applet.*;
public class AppletOne extends Applet implements Runnable {
String str = "This is a simple Banner ";
Thread t ;
boolean b;
public void init() {
setBackground(Color.gray);
setForeground(Color.yellow);
}
public void start() {
t = new Thread(this);
b = false;
t.start();
}
public void run () {
char ch;
for( ; ; ) {
try {
repaint();
Thread.sleep(200);
ch = str.charAt(0);
str = str.substring(1, str.length());
str = str + ch;
} catch(InterruptedException e) {}
}
}
public void paint(Graphics g) {
g.drawRect(1,1,300,150);
g.setColor(Color.yellow);
g.fillRect(1,1,300,150);
g.setColor(Color.red);
g.drawString(str, 1, 150);
}
}
Im even newbie to Thread concept please give me clear picture related on it. and give me some reference website to understand thread concept with applet and web based programming.
Upvotes: 0
Views: 94
Reputation: 34563
You can't call start()
on a thread that's already been started — you'll get an IllegalThreadStateException
. However, your program isn't doing that.
In your applet's start
method, you create a Thread
and pass the applet itself as the Runnable
argument. This means that when the thread is started, it'll call the applet's run
method. Then you call start()
on the thread to start it running. But you're calling start()
on the thread, not the applet, so you're not accidentally running the applet's own start
method again. There's no recursion happening here.
However, you're starting a thread and never stopping it. That's bad. Your applet needs to clean up after itself and not leave the thread running forever even after the applet itself has been destroyed. The way to do that is:
First, make your run
method actually respond to thread interruption. In your catch (InterruptedException e)
block, put a return
statement instead of just ignoring the exception. (See this article for more information on thread interruption.)
Second, add a stop()
method to your applet — like start()
, this is defined in the Applet
class, and it'll be called automatically when it's time for your applet to stop.
Third, in your new stop()
method, do t.interrupt()
followed by t.join()
. This will tell the thread that it should stop running, then wait for it to do so.
Upvotes: 3
Reputation: 2009
The following code segment is not entirely the best practice and start()
method should almost never be overridden.
public void start()
{
t = new Thread(this);
b = false;
t.start();
}
Rename your start()
method and call it from within the caller method.
Upvotes: 0