请看下面的程序
import java.lang.Runnable;
import java.lang.Thread;
public class DemoThread implements Runnable{
public DemoThread() {
TestThread testthread1 = new TestThread(this,"1");
TestThread testthread2 = new TestThread(this,"2");
TestThread testthread3 = new TestThread(this,"3");
testthread3.start();
testthread2.start();
testthread1.start();
}public static void main(String[] args) {
DemoThread demoThread1 = new DemoThread();
}public void run(){
TestThread t = (TestThread) Thread.currentThread();
try{
if (!t.getName().equalsIgnoreCase("1")) {
synchronized(this) {
wait();
}
}
while(true){
System.out.println("@time in thread"+ t.getName()+ "="+ t.increaseTime());
if(t.getTime()%10 == 0) {
synchronized(this) {
System.out.println("****************************************");
notify();
if ( t.getTime()==50 ) break;
wait();
}
}
}
}catch(Exception e){e.printStackTrace();}
}
}class TestThread extends Thread{
private int time = 0 ;
public TestThread(Runnable r,String name){
super(r,name);
}
public int getTime(){
return time;
}
public int increaseTime (){
return ++time;
}
}首先可以肯定的是testthread1先运行,testthread2和testthread3进入等待,这里有一个对象,那就是TestThread t = (TestThread) Thread.currentThread();这个t对象有3个线程监视着它,那么在testthread1进行notify的时候,按照这个api的定义,应该是随机的唤醒监视这个对象的一个线程,但是结果告诉我,每次testthread3都在testthread2前面,why?
而且当testthread3进行notify的时候,testthread1和testthread2进行争夺,应该这个结果也是随机的,但是你们可以运行一下,这个时候testthread1让给了testthread2,也就是顺序总是1,3,2
我想这个应该跟我new的顺序没关系吧?
但是当我先new testthread2的时候,结果是1,2,3
这个结果好像不符合notify的定义啊
jdk上是这么定义的
If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation
说了是arbitrary的
另外,我不知道我上面说的“ 这个t对象有3个线程监视着它”这个说法是否准确请各位赐教

解决方案 »

  1.   

    >按照这个api的定义,应该是随机的唤醒监视这个对象的一个线程,但是结果告诉我,每次testthread3都在testthread2前面,why?恐怕是这里的随机两个字误导了楼主,我想这里应该并没有什么随机可言。我想是这样的,JVM 规范没有规定多线程的抢先方式,因此 JVM 的实现厂商就可以根据自己的想法去实现。而实际上 JVM 的厂商的想法可能根本就不重要,在象 UNIX、LINUX、WINDOWS 这样的操作系统中,都有着各自的抢先规则,JVM 厂商只能入乡随俗。WINDOWS 的抢先机制是优先级,但在相同的优先级的情况下,想当然也应该是等待时间最成的线程会获得执行的机会。即便不是这样,应该也有其他的规则,而不会是完全随机的。