aspose file tools*
The moose likes Threads and Synchronization and the fly likes question about thread executing sequence Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "question about thread executing sequence" Watch "question about thread executing sequence" New topic
Author

question about thread executing sequence

zb cong
Ranch Hand

Joined: Jan 14, 2002
Posts: 416
hello
see my code bellow:

package threadtest;
import java.util.ArrayList;

public class SimpleThread implements Runnable{
private ArrayList values;
public SimpleThread(ArrayList values){
this.values=values;
}
public void run() {
for (int i = 0; i < 10; i++) {
this.values.add(new Integer(i).toString());
}
System.out.println("DONE! ");
}
}
****************************************************************************
package threadtest;
import java.util.ArrayList;
public class TwoThreadsDemo {
public static void main(String[] args) {
ArrayList values = new ArrayList();
Thread t1=new Thread(new SimpleThread(values));
Thread t2=new Thread(new SimpleThread(values));
t1.start();
t1.join();
t2.start();
t2.join();
System.out.println(values.size());
}
}

this program can finish the two thread instance first,then print the arraylist's size,but there is a question,that is the two thread instance don't execute AT THE SAME TIME,that is after the t1 died,the t2 begin to start.
but i want to the t1 and t2 execute at the same time just like the common multithread program,then print the arraylist's size after both of the two threads instance died.
how can i do?who can give me a code snippet?
thank you!
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

The join() method doesn't return until after the thread you call it on has exited. Generally you use join() to wait for a thread to finish, and only then continue on. So in your program, t2 isn't started until t1 is complete.
Simply move the first join() call after the second start() call, so you start both threads before joining either of them, and you'll be all set.


[Jess in Action][AskingGoodQuestions]
 
jQuery in Action, 2nd edition
 
subject: question about thread executing sequence