views:

42

answers:

1
class A implements Runnable{
   B b=new B();
 public void run(){
  while(true){
   System.out.println("H1"+Thread.currentThread().getName());
  }
 }

}

public class Test {
 public static void main(String[] str){
  A a1 =new A();
//  A a2 =new A();
//
  Thread t1 =new Thread(a1, "Vichi");
  Thread t2 =new Thread(a1,"Vishu");
  t1.start();
  t2.start();

 }
}

what will be the ans: 1) only one of them will get the chance to execute 2) both will get chance in arbitrary manner

please suggest possible ans with explations

+1  A: 

There's no synchronization shown in your code - both threads will run. Now the console access is probably synchronized somewhere, but basically I'd expect to see something like:

H1Vichi
H1Vichi
H1Vichi
H1Vichi
H1Vichi
H1Vishu
H1Vishu
H1Vishu
H1Vishu
H1Vichi
H1Vichi
H1Vichi
H1Vichi
H1Vishu
H1Vichi

etc - unpredictable, and dependent on the number of cores within your machine. I suspect you'll get blocks of output simply due to the console synchronization, but you shouldn't rely on it either way.

Basically there's no reason why the two independent threads wouldn't both run, just because they happen to share the same runnable target.

Jon Skeet