java三个线程同步...
时间:2010-08-19 来源:hero821
class a extends Thread{
private Kong k;
a(Kong k)
{
this.k=k;
}
public void run()
{
synchronized(k)
{
if(k.flag==false)
{
k.horsefly=0;
k.flag=true;
try{
k.wait();
}
catch(Exception e){}
}//三个线程的起始点
while(k.horsefly!=15){
try{
k.wait();
}
catch(Exception e){}
}
while(true){
k.horsefly=0;
System.out.println(k.horsefly);
for(int i=0;i<100000000;i++);
k.notifyAll();
try{
k.wait();
}
catch(Exception e){}
while(k.horsefly!=15){
try{
k.wait();
}
catch(Exception e){}
}
}
}
}
}
class b extends Thread{
private Kong k;
b(Kong k){this.k=k;}
public void run()
{
synchronized(k)
{
if(k.flag==false)
{
try{
k.wait();
}
catch(Exception e){}
}
while(k.horsefly!=0){
try{
k.wait();
}
catch(Exception e){}
}
while(true){
k.horsefly=10;
System.out.println(k.horsefly);
for(int i=0;i<100000000;i++);
k.notifyAll();
try{
k.wait();
}
catch(Exception e){}
while(k.horsefly!=0){
try{
k.wait();
}
catch(Exception e){}
}
}
}
}
}
class c extends Thread{
private Kong k;
c(Kong k){this.k=k;}
public void run()
{
synchronized(k)
{
if(k.flag==false)
{
try{
k.wait();
}
catch(Exception e){}
}
while(k.horsefly!=10){
try{
k.wait();
}
catch(Exception e){}
}
while(true){
k.horsefly=15;
System.out.println(k.horsefly);
for(int i=0;i<100000000;i++);
k.notifyAll();
try{
k.wait();
}
catch(Exception e){}
while(k.horsefly!=10){
try{
k.wait();
}
catch(Exception e){}
}
}
}
}
}
public class Kong{
public int horsefly;
boolean flag=false;
public static void main(String args[])
{
Kong k=new Kong();
a a1=new a(k);
b b1=new b(k);
c c1=new c(k);
a1.start();
b1.start();
c1.start();
}
}