package java_base.runnable.demo; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; //共享资源 class Resource { /** * Lock替换了synchronized * Condition 替换了wait、notify、notifyAll */ private Lock lock = new ReentrantLock(); private Condition condition_pro = lock.newCondition(); private Condition condition_con = lock.newCondition(); private String name; private int count = 1; private boolean flag = false;//资源标记位【很重要】 public void set(String name) throws InterruptedException { lock.lock(); try { while (flag) { condition_pro.await();//生产者等待 } this.name = name + "..." + count++; System.out.println(Thread.currentThread().getName() + "...生产者.." + this.name); flag = true; condition_con.signal();//唤醒消费者 } finally { lock.unlock();// 在finally中释放锁 } } public void out() throws InterruptedException { lock.lock(); try { while (!flag) { condition_con.await();//消费者等待 } System.out.println(Thread.currentThread().getName() + ".........消费者----" + name); flag = false; condition_pro.signal();//唤醒生产者 } finally { lock.unlock(); } } } //生产者 class Producer implements Runnable { private Resource r; public Producer(Resource r) { this.r = r; } public void run() { while (true) { try { r.set("商品"); } catch (InterruptedException e) { e.printStackTrace(); } } } } //消费者 class Consumer implements Runnable { private Resource r; public Consumer(Resource r) { this.r = r; } public void run() { while (true) { try { r.out(); } catch (InterruptedException e) { e.printStackTrace(); } } } } public class ProducerConsumerDemo { public static void main(String[] args) { Resource r = new Resource(); Producer pro = new Producer(r); Consumer con = new Consumer(r); Thread t1 = new Thread(pro); Thread t2 = new Thread(pro); Thread t3 = new Thread(con); Thread t4 = new Thread(con); t1.start(); t2.start(); t3.start(); t4.start(); } }
java多线程通信-生产者消费者
猜你喜欢
转载自blog.csdn.net/cellmemaster/article/details/80458039
今日推荐
周排行