question about thread execute sequence

Discussions

General J2EE: question about thread execute sequence

  1. question about thread execute sequence (2 messages)

    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!
  2. question about thread execute sequence[ Go to top ]

    t1.start();
    t2.start();
     
    t1.join();
    t2.join();
  3. question about thread execute sequence[ Go to top ]

    You need to change the code as Stephan suggested. I would also note that ArrayList is not thread-safe, and modifying it from two threads at the same time is risky. You can fix it by replacing:
    ArrayList values = new ArrayList();
    With:
    List values = Collections.synchronizedList(new ArrayList());
    You also need to change the SimpleThread class to accept List instead of ArrayList (which is generally a good idea regardless of the synchronization issue).

    Gal