import java.util.concurrent.locks.*;
class Resource
{
private String name;
private int count=1;
boolean flag=false;
Lock lock=new ReentrantLock();
Condition producer_con=lock.newCondition();
Condition consumer_con=lock.newCondition();
public void set(String name){
lock.lock();
try{
while(flag)
//try{wait();}catch(InterruptedException e){}
try{producer_con.await();}catch(InterruptedException e){}
this.name=name+count;
count++;
System.out.println(Thread.currentThread().getName()+"..生产者.."+this.name);
flag=true;
consumer_con.signal();}
finally{
lock.unlock();
}
}
public void out(){
lock.lock();
try{
while(!flag)
//try{wait();}catch(InterruptedException e){}
try{consumer_con.await();}catch(InterruptedException e){}
System.out.println(Thread.currentThread().getName()+"..消费者.........."+this.name);
flag=false;
producer_con.signal();}
finally{
lock.unlock();
}
}
}
class Producer implements Runnable
{
Resource r;
Producer(Resource r){
this.r=r;
}
public void run(){
while(true){
r.set("烤鸭");
}
}
}
class Consumer implements Runnable
{
Resource r;
Consumer(Resource r){
this.r=r;
}
public void run(){
while(true){
r.out();
}
}
}
class ProducerConsumerDemo
{
public static void main(String[] args)
{
Resource r=new Resource();
Producer pro=new Producer(r);
Consumer con=new Consumer(r);
Thread t0=new Thread(pro);
Thread t1=new Thread(pro);
Thread t2=new Thread(con);
Thread t3=new Thread(con);
t0.start();
t1.start();
t2.start();
t3.start();
}
}
上面程序编译后会出现如下报错:
F:\javatest>javac ProducerConsumerDemo.java
ProducerConsumerDemo.java:9: 错误: 不兼容的类型
Lock lock=new ReentrantLock();
^
需要: Lock
找到: ReentrantLock
ProducerConsumerDemo.java:10: 错误: 找不到符号
Condition producer_con=lock.newCondition();
^
符号: 方法 newCondition()
位置: 类型为Lock的变量 lock
ProducerConsumerDemo.java:11: 错误: 找不到符号
Condition consumer_con=lock.newCondition();
^
符号: 方法 newCondition()
位置: 类型为Lock的变量 lock
ProducerConsumerDemo.java:13: 错误: 找不到符号
lock.lock();
^
符号: 方法 lock()
位置: 类型为Lock的变量 lock
ProducerConsumerDemo.java:24: 错误: 找不到符号
lock.unlock();
^
符号: 方法 unlock()
位置: 类型为Lock的变量 lock
ProducerConsumerDemo.java:28: 错误: 找不到符号
lock.lock();
^
符号: 方法 lock()
位置: 类型为Lock的变量 lock
ProducerConsumerDemo.java:37: 错误: 找不到符号
lock.unlock();
^
符号: 方法 unlock()
位置: 类型为Lock的变量 lock
7 个错误