class Output implements Runnable
{
private static final int THREAD_COUNT = 4;
Resource r;
static int times = 0;
static int ifTimes = 0;
int flag; Output( Resource r, int flag )
{
this.r = r;
this.flag = flag;
} public void run()
{
while( times < 100 )
{
++times;
synchronized( r )
{
if ( r.flag != this.flag )
{
++ifTimes;
try
{
r.wait();
}
catch ( Exception e )
{

}
}
r.show( times, ifTimes ); r.flag = ( r.flag + 1 ) % THREAD_COUNT;
r.notify();
}
}
}
}class Resource
{
int flag = 0;
public void show( int times, int ifTimes )
{
System.out.println( "现在输出的线程是................" + flag + "    这是第 " + times + " 次运行,if运行了 " + ifTimes + " 次" );
}
}class SpecialDemo 
{
public static void main(String[] args) 
{
Resource r = new Resource();
Thread t0 = new Thread( new Output( r, 0 ) );
Thread t1 = new Thread( new Output( r, 1 ) );
Thread t2 = new Thread( new Output( r, 2 ) );
Thread t3 = new Thread( new Output( r, 3 ) );

t0.start();
t1.start();
t2.start();
t3.start();
}
}
最近在学java的线程,好奇写了一小段。
4个线程,一共运行循环100次。同步之后输出运行的线程编号+运行次数。
现象是,计数变量times很平稳的从1到走到了100,其中就丢失了3次,并且没有重复,也就是说判断机制每次循环只判断了一次。那么我的疑问也就来了:
随意取一个中间的状态,比如0线程正常运行时,其他3个线程正挂起,那么0调用notify了之后,为什么会优先调用到1线程(如果调用到其他2个线程,则直接会再次挂起并死锁)?如果说是按wait装入的顺序来notify的话,那么随机调用线程的属性会造成wait的顺序也是随机的;如果说是按照线程顺序的话我修改过代码也没有发生过死锁。
请比较熟悉的大师来告诉我下比较详细的wait和notify机制。
另外我用的是win7的32位系统,jdk版本是1.7.0_09waitnotify顺序底层代码判断机制