This week's book giveaway is in the Cloud/Virtualizaton forum.
We're giving away four copies of Mesos in Action and have Roger Ignazio on-line!
See this thread for details.
Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

question about thread executing sequence

 
zb cong
Ranch Hand
Posts: 416
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic