使用notify方法只唤醒一个线程(任意唤醒一个),
而notifyAll则唤醒该对象监视器上等待的所有线程,被唤醒的线程将以常规方式与在该对象上主动同步的其他所有线程进行竞争
/////////////////////////////////////这里用notify会有问题,但是用notifyAll就可以实现.但对于notifyAll我还是不太懂
public class TraditionalThreeCommunicationTest
{/**
* Condition类似于Object对象的wait和notify方法的功能(通信) 可以使用多个Condition实现相互通信
* */
/**
* 一个重要的设计思想(高内聚):
*
* 把有关联(用到了同一份数据(锁也是资源),或共同算法(计算公式))的若干个方法应该归在一个类身上, 这种设计正好体现了高类聚和程序的健壮性
*
* ----锁是上在代表要操作的资源的类的内部方法中,而不是线程方法中!
* */
public static void main(String[] args)
{
final Business2 bu = new Business2();
new Thread()
{
@Override
public void run()
{
// synchronized(TraditionalThreadWaitAndNotify.class){
for (int i = 0; i < 50; i++)
{
/*
* for(int j=0;j<10;j++){
* System.out.println("sub Thread :"+j+" of "+i); }
*/
bu.sub2(i);
}
// }
}
}.start();
new Thread()
{
@Override
public void run()
{
// synchronized(TraditionalThreadWaitAndNotify.class){
for (int i = 0; i < 50; i++)
{
/*
* for(int j=0;j<10;j++){
* System.out.println("sub Thread :"+j+" of "+i); }
*/
bu.sub3(i);
}
// }
}
}.start();
/*
* for(int i=0;i<100;i++){ System.out.println("main thread :"+i); }
*/
for (int i = 0; i < 50; i++)
{
bu.main(i);
}
}
}
class Business2
{
private int sub = 2;// 让老2先走
public synchronized void sub2(int i)
{
while (sub != 2)
{// while比if更健壮,while会判断两次
try
{
this.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
for (int j = 0; j < 10; j++)
{
System.out.println("sub2 Thread :" + j + " of " + i);
}
sub = 3;
// this.notify();
this.notifyAll();
}
public synchronized void sub3(int i)
{
while (sub != 3)
{// while比if更健壮,while会判断两次
try
{
this.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
for (int j = 0; j < 10; j++)
{
System.out.println("sub3 Thread :" + j + " of " + i);
}
sub = 1;
//this.notify();
this.notifyAll();
}
public synchronized void main(int i)
{
while (sub != 1)
{// while比if更健壮,while会判断两次
try
{
this.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
for (int j = 0; j < 100; j++)
{
System.out.println("main thread :" + j + " of " + i);
}
sub = 2;
this.notifyAll();
}
}