-2

Write a thread that counts 1 to 10 and another thread that counts 1 to 10, one after another.

For eg: Thread1 Output: 1 Thread2 Output:1 Thread1 Output:2 Thread2 Output:2

I have written below code

public class Test1 extends Thread
{
public void run(){
    for(int i=1;i<=10;i++){
        //System.out.println(i);
        try{
            System.out.println(Thread.currentThread().getName()+"+i);
            Thread.sleep(500);

        }catch(Exception e){
            System.out.println(e);

        }
    }
}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Test1 t1=new Test1();
    Test1 t2=new Test1();
    //Test1 t3=new Test1();
    t1.start();
    t2.start();
    //t3.start();

}

}   

Got the output as:-
Thread-1 1
Thread-0 1
Thread-1 2
Thread-0 2
Thread-0 3
Thread-1 3
Thread-0 4
Thread-1 4
Thread-1 5
Thread-0 5
Thread-1 6
Thread-0 6
Thread-1 7
Thread-0 7
Thread-1 8
Thread-0 8
Thread-1 9
Thread-0 9
Thread-1 10
Thread-0 10

But the output isn't in sequence I want output as: Thread1 Output:1 Thread2 Output:1 Thread1 Output:2 Thread2 Output:2

  • I am new to thread concept.Could you help me to achieve Synchronize,so that threads will print one after one till last sequence – Java learner Aug 16 '16 at 08:46

1 Answers1

-1

You can't influence this... 2 threads working parallel are not deterministic...

That means if the cpu has some free resources it will take a thread and do "a step"... but you can't influence which thread it will be.

Take a look at: Can a multi-threaded program ever be deterministic?

Community
  • 1
  • 1
SleepyX667
  • 670
  • 9
  • 21