H
hilz
Hi group.
I am trying to learn how to make a thread wait until another thread
terminates.
I have created a simple example that compiles and runs (please see at
the end of this message, and beware of text-wrapping!).
I have two threads t1 and t2.
t1 prints a message every second, and terminates after 10 messages.
t2 should wait till t1 has ended and then print a message to inform me
of that.
After some playing around, i could not get it to work. i think i should
put something at the place where i put the following comment:
//I think i need to put something here!
One of the things i tried was to put "t1.wait();" but that gives a
compile error that t1 should be declared final. So I declared t1 as
final, and that did not help. the message from t2 still appears before
any messages from t1.
Any help is greatly appreciated.
thanks
hilz.
public class NewClass {
public NewClass() {
Thread t1 = new Thread(new Runnable(){
public void run(){
try{
for (int i=0;i<10;i++){
Thread.sleep(1000);
System.out.println("Thread t1: "+i);
}
}catch(Exception exp){exp.printStackTrace();}
}
});
Thread t2 = new Thread(new Runnable(){
int counter=0;
public void run(){
try{
//I think i need to put something here!
System.out.println("This message comes to you from
thread t2 to inform you that t1 has terminated.");
}catch(Exception exp){exp.printStackTrace();}
}
});
t1.start();
t2.start();
}
public static void main(){
new NewClass();
}
}
I am trying to learn how to make a thread wait until another thread
terminates.
I have created a simple example that compiles and runs (please see at
the end of this message, and beware of text-wrapping!).
I have two threads t1 and t2.
t1 prints a message every second, and terminates after 10 messages.
t2 should wait till t1 has ended and then print a message to inform me
of that.
After some playing around, i could not get it to work. i think i should
put something at the place where i put the following comment:
//I think i need to put something here!
One of the things i tried was to put "t1.wait();" but that gives a
compile error that t1 should be declared final. So I declared t1 as
final, and that did not help. the message from t2 still appears before
any messages from t1.
Any help is greatly appreciated.
thanks
hilz.
public class NewClass {
public NewClass() {
Thread t1 = new Thread(new Runnable(){
public void run(){
try{
for (int i=0;i<10;i++){
Thread.sleep(1000);
System.out.println("Thread t1: "+i);
}
}catch(Exception exp){exp.printStackTrace();}
}
});
Thread t2 = new Thread(new Runnable(){
int counter=0;
public void run(){
try{
//I think i need to put something here!
System.out.println("This message comes to you from
thread t2 to inform you that t1 has terminated.");
}catch(Exception exp){exp.printStackTrace();}
}
});
t1.start();
t2.start();
}
public static void main(){
new NewClass();
}
}