多线程 ReentrantLock"/>
多线程 ReentrantLock
产品
package proCus;
/** created by sj 2019年8月21日*/
public class Product {int id;public Product(int id) {this.id = id;}@Overridepublic String toString() {return "Product [id=" + id + "]";}}
容器 及 测试
package proCus;import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;/** created by sj 2019年8月21日*/
public class SynStack { //pro Cus 通信private Lock lock = new ReentrantLock(false);Condition proCond = lock.newCondition();Condition cusCond = lock.newCondition();int MAX = 5; Queue<Product> ps = new LinkedList<>();public void push(Product p) { //送入产品try {lock.lock();while(ps.size() == MAX ) {try {proCond.await(); //} catch (InterruptedException e) {e.printStackTrace();}}ps.add(p);cusCond.signalAll();}finally {lock.unlock();}}public Product pop() { //取出产品try {lock.lock();while(ps.size() == 0) { //判断ps大小时,用whiletry {cusCond.await();} catch (InterruptedException e) {e.printStackTrace();}}Product p = ps.peek();ps.remove();//唤醒在 proCond的线程proCond.signalAll();return p;} finally {lock.unlock();}}public static void main(String[] args) { SynStack c = new SynStack();for (int i = 0; i < 2; i++) { //两个生产者new Thread(()->{for (int j = 0; j < 10; j++) {Product p = new Product(j);c.push(p);System.out.println(Thread.currentThread().getName()+" produce "+p);}},"producer-"+i).start(); }for (int i = 0; i < 2; i++) {new Thread(()->{for (int j = 0; j < 10; j++) {Product p = c.pop();System.out.println(Thread.currentThread().getName()+" cusume " + p);}}, "customer-"+i).start(); }}}
更多推荐
多线程 ReentrantLock
发布评论