本帖最后由 朱神必 于 2014-4-1 18:04 编辑
用lock加锁编的生产者消费者,但是编译卡住,看提示貌似是导包的问题,可这样导有什么问题啊。。。?代码整段上来,应该只是导包问题,谢谢。- /**
- 生产者消费者问题:
- */
- import java.util.*;
- class Resource
- {
- private String name;
- private int count = 1;
- private boolean flag = false;
- //创建锁对象
- Lock lock = new ReentrantLock();
- //给lock配两把锁
- Condition pro_con = lock.newCondition();
- Condition cus_con = lock.newCondition();
- public void set(String name){
- lock.lock();
- try{
- while(flag)
- try{pro_con.await();}catch(InterruptedException e){}
- this.name = name+count;
- count++;
- System.out.println(Thread.currentThread().getName()+"——生产者——"+this.name);
- flag = true;
- cus_con.signal();
- }
- finally{
- lock.unlock();
- }
- }
- public void out(){
- lock.lock();
- try{
- while(!flag)
- try{cus_con.await();}catch(InterruptedException e){}
- System.out.println(Thread.currentThread().getName()+"——消费者————"+this.name);
- flag = false;
- pro_con.signal();
- }
- finally{
- lock.unlock();
- }
- }
- }
- class Pro implements Runnable{
- private Resource r;
- Pro(Resource r){
- this.r = r;
- }
- public void run(){
- while(true)
- r.set("BMW");
- }
- }
- class Cus implements Runnable{
- private Resource r;
- Cus(Resource r){
- this.r = r;
- }
- public void run(){
- while(true){
- r.out();
- }
- }
- }
- class Producer1{
- public static void main(String[] args){
- Resource r = new Resource();
- Pro p = new Pro(r);
- Cus c = new Cus(r);
- Thread t1 = new Thread(p);
- Thread t2 = new Thread(c);
- Thread t3 = new Thread(c);
- Thread t4 = new Thread(c);
- t1.start();
- t2.start();
- t4.start();
- t3.start();
- }
- }
复制代码
|
|