这个程序其实之前有写过,只是那个时候出现了一些问题,所以这几天一直在等待大神帮我解决其中的问题,最后发现问题竟然是自己少了一个”!”….当我知道后才发现郁闷了,所以平时必须要仔细的去处理各种问题才行啊。
废话不多说,先把程序放出来,大家慢慢的欣赏。
import java.util.concurrent.locks.*;
class Zhiyuan
{
private String name;
private int constet=1;
private boolean flag=false;
Lock lock=new ReentrantLock();
Condition mm=lock.newCondition();
Condition nn=lock.newCondition();
public void set(String name){
lock.lock();
try{
while(flag)
try{
mm.await();
}
catch (InterruptedException e){
}
this.name=name+constet;
constet++;
System.out.println(Thread.currentThread().getName()+”…生产者5.0.。。”+this.name);
flag=true;
nn.signal();
}
finally
{
lock.unlock();
}
}
public void out(){
lock.lock();
try{
while(!flag)
try{
nn.await();
}
catch (InterruptedException e){
}
System.out.println(Thread.currentThread().getName()+”…生产者5.0.。。”+this.name);
flag=false;
mm.signal();
}
finally
{
lock.unlock();
}
}
}
class Scz implements Runnable{
private Zhiyuan z;
Scz(Zhiyuan z){
this.z=z;
}
public void run(){
while(true){
z.set(“北京烤鸭”);
}
}
}
class Xfz implements Runnable{
private Zhiyuan z;
Xfz(Zhiyuan z){
this.z=z;
}
public void run(){
while(true){
z.out();
}
}
}
public class Demo{
public static void main(String[] args){
Zhiyuan z=new Zhiyuan();
Scz s=new Scz(z);
Xfz x=new Xfz(z);
Thread t0=new Thread(s);
Thread t1=new Thread(s);
Thread t2=new Thread(x);
Thread t3=new Thread(x);
t0.start();
t1.start();
t2.start();
t3.start();
}
}
评论前必须登录!
注册