0

While running the following code random results are coming. Random results are like:

  • While I run the code the result 1st came out was

    B=1, B=2, B=3, B=4, B=5, exit from B, A=1, A=2, A=3, A=4, A=5, exit from A.

  • Next time

    B=1, B=2, A=1, A=2, A=3, A=4, A=5, B=3, B=4, A=5, exit from B, exit from A.

Why?

class A extends Thread

{

 public void run()

 {

  for(int i=1;i<=5;i++)

  {


   if(i==3) yield();

   System.out.println("A="+i);

  }

  System.out.println("Exit from A");

 }

}

class B extends Thread

{

 public void run()

 {

  for(int j=1;j<=5;j++)

  {

   System.out.println("B="+j);

  }

  System.out.println("Exit from B");

 }

}

class T 

{

 public static void main(String args[])

 {

  A obj1=new A();

  B obj2=new B();


  obj1.start();

  obj2.start();    

 }

}
Supun Wijerathne
  • 11,964
  • 10
  • 61
  • 87
Bidyut
  • 1
  • 2

2 Answers2

0

You cannot guarantee the order of execution. Calling start() doesn't mean run() will be called immediately, it depends on thread scheduler when it chooses to run your thread.

You don't use synchronization at all so you never know what thread intercepts execution.

mchern1kov
  • 450
  • 3
  • 10
0

You have not used any control(locks, semaphores, barriers etc.) over the synchronization of threads. So basically you can't expect any definite output of your code.

You can never guess the order of execution a set of freely running threads. It pretty much depends on

  • How underneath Operating system handles system level thread execution (Windows, Linux, Unix have different mechanisms).
  • Your underneath hardware (Single-core vs multi-core, hyper-threading etc).
  • Mostly the status of the system when you execute your program (how other processes have utilized the system at the time the program is in execution).

From your code, I think you are trying experiment the way yield(); works. And your code would not give you any support. Sadly, the code you are trying won't help you. This question has 3, 4 good answers and examples for that purpose. :))

Community
  • 1
  • 1
Supun Wijerathne
  • 11,964
  • 10
  • 61
  • 87