wood burning stoves
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
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "question about thread executing sequence" Watch "question about thread executing sequence" New topic

question about thread executing sequence

zb cong
Ranch Hand

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

package threadtest;
import java.util.ArrayList;

public class SimpleThread implements Runnable{
private ArrayList values;
public SimpleThread(ArrayList 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));

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

Joined: Jul 08, 2003
Posts: 24199

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]
I agree. Here's the link: http://aspose.com/file-tools
subject: question about thread executing sequence
It's not a secret anymore!