做出来了,没有用到Lock接口。。。只用同步代码块实现了
class ThreadPrint implements Runnable
{
int count=1;
int k=1;
private void sop()
{
for(int i=0;i<5;i++)
{
System.out.println(Thread.currentThread().getName()+":"+count++);
}
}
public void run()
{
while(count<=75)
{
synchronized(this)
{
if(k==1)
{
if(Thread.currentThread().getName().equals("线程1"))
{
sop();
k=(k+1)%3;
this.notifyAll();
try{this.wait();}catch(Exception e){}
}
else
{
try{this.wait();}catch(Exception e){};
}
}
else if(k==2)
{
if(Thread.currentThread().getName().equals("线程2"))
{
sop();
k=(k+1)%3;
this.notifyAll();
try{this.wait();}catch(Exception e){}
}
else
{
try{this.wait();}catch(Exception e){};
}
}
else
{
if(Thread.currentThread().getName().equals("线程3"))
{
sop();
k=(k+1)%3;
if(count>75)
{
this.notifyAll();
}
else
{
this.notifyAll();
try{this.wait();}catch(Exception e){}
}
}
else
{
try{this.wait();}catch(Exception e){};
}
}
}
}
}
}
public class ThreadTest
{
public static void main(String args [])throws Exception
{
ThreadPrint tp=new ThreadPrint();
Thread t1=new Thread(tp,"线程1");
Thread t2=new Thread(tp,"线程2");
Thread t3=new Thread(tp,"线程3");
t1.start();
t2.start();
t3.start();
}
}
|