开发者

multithreading scheduling related java [closed]

开发者 https://www.devze.com 2022-12-25 01:31 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and 开发者_高级运维 cannot be reasonably answered in its current for
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and 开发者_高级运维 cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 10 years ago.
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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消