多线程 ReentrantLock

编程入门 行业动态 更新时间:2024-10-24 14:22:53

<a href=https://www.elefans.com/category/jswz/34/1767532.html style=多线程 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

本文发布于:2023-07-28 18:02:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1269929.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多线程   ReentrantLock

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!