Java并发之Condition 并发同步控制
1 package com.thread.test.thread; 2 3 import java.util.PriorityQueue; 4 import java.util.concurrent.locks.Condition; 5 import java.util.concurrent.locks.Lock; 6 import java.util.concurrent.locks.ReentrantLock; 7 8 /** 9 * Created by windwant on 2016/10/21. 10 */ 11 public class MyLockCondition{ 12 13 private int queueSize = 10; 14 private PriorityQueue<Integer> queue = new PriorityQueue<Integer>(queueSize); 15 private Lock lock = new ReentrantLock(); 16 private Condition notFull = lock.newCondition(); 17 private Condition notEmpty = lock.newCondition(); 18 19 public static void main(String[] args) { 20 MyLockCondition test = new MyLockCondition(); 21 Producer producer = test.new Producer(); 22 Consumer consumer = test.new Consumer(); 23 24 producer.start(); 25 consumer.start(); 26 } 27 28 class Consumer extends Thread{ 29 30 @Override 31 public void run() { 32 consume(); 33 } 34 35 private void consume() { 36 while(true){ 37 lock.lock(); 38 try { 39 while(queue.size() == 0){ 40 try { 41 System.out.println("队列空,等待数据"); 42 notEmpty.await(); 43 } catch (InterruptedException e) { 44 e.printStackTrace(); 45 } 46 } 47 queue.poll(); //每次移走队首元素 48 notFull.signal(); 49 System.out.println("从队列取走一个元素,队列剩余"+queue.size()+"个元素"); 50 } finally{ 51 lock.unlock(); 52 } 53 } 54 } 55 } 56 57 class Producer extends Thread{ 58 59 @Override 60 public void run() { 61 produce(); 62 } 63 64 private void produce() { 65 while(true){ 66 lock.lock(); 67 try { 68 while(queue.size() == queueSize){ 69 try { 70 System.out.println("队列满,等待有空余空间"); 71 notFull.await(); 72 } catch (InterruptedException e) { 73 e.printStackTrace(); 74 } 75 } 76 queue.offer(1); //每次插入一个元素 77 notEmpty.signal(); 78 System.out.println("向队列取中插入一个元素,队列剩余空间:"+(queueSize-queue.size())); 79 } finally{ 80 lock.unlock(); 81 } 82 } 83 } 84 } 85 }
项目地址:https://github.com/windwant/windwant-demo/tree/master/thread-demo