Thread2 waits Thread1 to complete to start Problem? Java

George Dim :

So I have a simple code that i want to print the value i 10 times with Thread1 , after that 10 times of Thread2 and at the end , print the count ( it should be 20). I am using the ".join()" but the result is excecuting random times of Thread1 and Thread2 and then the Sum is correct. How can is it possible to print first all the Thread's1 loop and then the Tread's2 ??

class MyClass extends Thread {  

     public static synchronized void incount() {
         SimpleThreads.count++;
     } 
        public void run() { 

            for(int i=0; i<10; i++) { 
                    incount();  
                    System.out.println(Thread.currentThread().getId()+" value : " + i);
            }
        }           
    }

public class SimpleThreads {

     static int count=0;

    public static void main(String[] args) {

        MyClass thread1 =new MyClass();
        MyClass thread2 =new MyClass();

        thread1.start(); 
        thread2.start();
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(" Sum : "+count);
    }
}

The Result :

11 value : 0
10 value : 1
11 value : 1
10 value : 2
11 value : 2
10 value : 3
11 value : 3
11 value : 4
11 value : 5
11 value : 6
11 value : 7
11 value : 8
11 value : 9
10 value : 4
10 value : 5
10 value : 6
10 value : 7
10 value : 8
10 value : 9
 Sum : 20
Shivam Puri :

You are starting Thread2 before calling the join() on thread1.
That is why your both threads are basically running simultaneously and your join is not affecting the run() of any other the 2 threads.

Try to change your start and join calling code to something like this;

try{
    thread1.start();
    thread1.join();
    thread2.start();
}

You shouldn't need to call join() on thread2 in this case.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=404821&siteId=1