多线程--简单生产者与消费者(Lock锁)

Posted twqwe

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程--简单生产者与消费者(Lock锁)相关的知识,希望对你有一定的参考价值。

前两篇的生产者与消费者(多线程)运用的是synchronized进行同步锁的,本次将运用JDK1.5提供的Lock锁。

它 将synchronized替换成了Lock将Object中的wait notify notifyAll替换成了Condition对象,

Condition可以被Lock获取,

可以创建多个Condition对象,只唤醒对方操作。

 

具体代码如下:

package cn.zz;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Resource3 {
private String name;
private int count;
private boolean flag = false;
private Lock lock = new ReentrantLock();
Condition condition_Pro = lock.newCondition();
Condition condition_Con = lock.newCondition();

public void set(String name) throws Exception {
lock.lock();
try {
while (flag) {
condition_Pro.await();
this.name = name + "..." + count++;
System.out.println(Thread.currentThread().getName() + "...生产者"
+ this.name);
flag = true;
}
} finally {
condition_Con.signal();
}
}

public void out() throws Exception {
lock.lock();
try {
while (!flag) {
condition_Pro.await();
this.name = name + "..." + count++;
System.out.println(Thread.currentThread().getName()
+ "...消费者....." + this.name);
flag = false;
}
} finally {
condition_Pro.signal();
}

}

class Producer3 implements Runnable {
Resource3 res3;

public Producer3(Resource3 res3) {
this.res3 = res3;
}

@Override
public void run() {
while (true) {
try {
res3.set("商品");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

}

class Consumer3 implements Runnable {
Resource3 res3;

public Consumer3(Resource3 res3) {
this.res3 = res3;
}

@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
res3.out();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}

public class ProducerAndConsumer3 {
public void main(String[] args) {
Resource2 res2 = new Resource2();

new Thread(new Producer2(res2)).start();
new Thread(new Producer2(res2)).start();
new Thread(new Consumer2(res2)).start();
new Thread(new Consumer2(res2)).start();

}
}
}

技术分享图片

运行结果如上。



































































以上是关于多线程--简单生产者与消费者(Lock锁)的主要内容,如果未能解决你的问题,请参考以下文章

JUC - 多线程之Synchronized和Lock锁;生产者消费者模式

JavaLearn#(16)多线程提升训练:生产者和消费者问题Lock锁ReadWriteLockBlockingQueuevolatile线程池线程同步练习

python 多线程笔记-- 生产者/消费者模式

JavaLearn#(16)多线程提升训练:生产者和消费者问题Lock锁ReadWriteLockBlockingQueuevolatile线程池线程同步练习

多线程JUC并发篇常见面试详解

“全栈2019”Java多线程第二十六章:同步方法生产者与消费者线程