0

Is there any situation when output will not be A/B/BC/AD (/ is new line)? Is it possible that the second Thread starts before first?

public class JavaApplication6 extends Thread{
final StringBuffer sb1 = new StringBuffer();
final StringBuffer sb2 = new StringBuffer();

public static void main(String[] args) throws InterruptedException {
    final JavaApplication6 h = new JavaApplication6();
    new Thread(){
        public void run(){
            synchronized(this){
                h.sb1.append("A");
                h.sb2.append("B");
                System.out.println(h.sb1);
                System.out.println(h.sb2);
            }
        }
    }.start();
    new Thread(){
        public void run(){
            synchronized(this){
                h.sb1.append("D");
                h.sb2.append("C");
                System.out.println(h.sb2);
                System.out.println(h.sb1);
            }
        }
    }.start();           
}}    
Davidm176
  • 163
  • 1
  • 12
  • Possible duplicate of [Execution order of multiple threads](http://stackoverflow.com/questions/13228164/execution-order-of-multiple-threads) and [this](http://stackoverflow.com/questions/41356539/java-thread-order-of-execution) – Robin Topper May 02 '17 at 09:56

2 Answers2

0

Yes, second thread could start before first.

This can be because thread scheduler starts threads in unpredictable manner.

Moreover: first could start first, but finish last, because of switches between threads (made by mentioned thread scheduler).

Even if you run this app many times and 'prove' that order will be the same, there is no guarantee that this order will not change next run.

Max Farsikov
  • 2,451
  • 19
  • 25
0

Yes, It is possible second thread can start before first thread. It totally depends on the thread scheduler. Once the threads are created they move to runnable state, then it's the responsibility of the thread scheduler which thread to execute. There is no guarantee which thread will start and complete first. You can try this behavior by executing this method in a loop-

public static void abc() throws InterruptedException {
    final JavaApplication6 h = new JavaApplication6();
    new Thread(){
        public void run(){
            synchronized(this){
              System.out.println("T-10000000000");
            }
        }
    }.start();
    new Thread(){
        public void run(){
            synchronized(this){
              System.out.println("T-2");
            }
        }
    }.start();           
}}

public class JavaApplication61 {
    public static void main(String ar[]) throws InterruptedException{
        for(int i=0; i<100;i++){
            JavaApplication6.abc();
        }
    }

}
HOSHIYAR
  • 61
  • 3