本帖最后由 yting_xmei1129 于 2013-10-12 23:42 编辑
下面是代码、、、- package yting.day11.thread;
- import java.util.concurrent.locks.*;
- public class LockCondition_ProducerConsumerDemo1 {
- public static void main(String[] args) {
- Resource_all res = new Resource_all();
-
- //两个生产者
- new Thread(new Producer_all(res)).start();
- new Thread(new Producer_all(res)).start();
-
- //两个消费者
- new Thread(new Consumer_all(res)).start();
- new Thread(new Consumer_all(res)).start();
-
- }
- }
- class Resource_all {
- private String name;
- private int count = 1;
- private boolean flag = false;
- private Lock lock = new ReentrantLock();
- private Condition cond = lock.newCondition();
-
- public synchronized void setName(String name) {
- lock.lock();
- try {
- while (flag) {
- cond.await();
- }
- this.name = name + "---" + count++;
- System.out.println(Thread.currentThread().getName() + "...生产者..." + this.name);
- flag = true;
- cond.signalAll();
- } catch (InterruptedException e) {
- e.printStackTrace();
- } finally {
- lock.unlock();
- }
- }
-
- public synchronized void print(){
- lock.lock();
- try {
- while (!flag) {
- cond.await();
- }
- System.out.println(Thread.currentThread().getName() + "...消费者.........." + name);
- flag = false;
- cond.signalAll();
- } catch (InterruptedException e) {
- e.printStackTrace();
- } finally {
- lock.unlock();
- }
- }
- }
- class Producer_all implements Runnable {
- private Resource_all r;
-
- public Producer_all(Resource_all r) {
- this.r = r;
- }
- @Override
- public void run() {
- while(true){
- r.setName("商品");
- }
- }
- }
- class Consumer_all implements Runnable {
- private Resource_all r;
-
- public Consumer_all(Resource_all r) {
- this.r = r;
- }
- @Override
- public void run() {
- while(true){
- r.print();
- }
- }
-
- }
复制代码 运行的时候会一直等在那里,求大神解答,感激不尽、、、
|