java线程之间通信,多种方式实现生产者消费者模式
2021-04-19 09:27
标签:condition stack 生产 pre inter read cat getname highlight 实现需求:两个线程交替打印1,0,打印10轮 java多线程口诀: wait:使当前线程阻塞 notify,notifyAll唤醒当前线程 输出结果 输出结果 主要是熟悉Lock和Condition的使用 Lock和Condition相比于synchronized,能够精确唤醒 需求:三个线程A,B,C顺序打印,A打印5次,B打印10次,C打印15次,10轮 java线程之间通信,多种方式实现生产者消费者模式 标签:condition stack 生产 pre inter read cat getname highlight 原文地址:https://www.cnblogs.com/lt123/p/13290098.htmljava多线程之间的通信,及使用多种方式实现生产者消费者模式
方式一:使用synchronized和Object的wait和notifyAll方法
/**
* 两个线程交替打印1,0 打印10轮
*
* @author Administrator
* @version 1.0 2020年7月12日
* @see ProdConsumerDemo1
* @since 1.0
*
*/
class ShareData1 {
public int number = 0;
public synchronized void increment() throws Exception {
while (number != 0) {
this.wait();
}
number++;
System.out.println(Thread.currentThread().getName() + " " + number);
this.notifyAll();
}
public synchronized void decrement() throws InterruptedException {
while (number != 1) {
this.wait();
}
number--;
System.out.println(Thread.currentThread().getName() + " " + number);
this.notifyAll();
}
}
public class ProdConsumerDemo1 {
public static void main(String[] args) {
ShareData1 shareData = new ShareData1();
new Thread(() -> {
for (int i = 0; i {
for (int i = 0; i
A 1
B 0
A 1
B 0
A 1
B 0
A 1
B 0
A 1
B 0
A 1
B 0
A 1
B 0
A 1
B 0
A 1
B 0
A 1
B 0
方式二:使用jdk1.8的Lock和Condition
class ShareData2 {
private int number = 0;
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void increment() throws Exception {
lock.lock();
try {
while (number != 0) {
condition.await();
}
number++;
System.out.println(Thread.currentThread().getName() + " " + number);
condition.signalAll();
} finally {
lock.unlock();
}
}
public void decrement() throws InterruptedException {
lock.lock();
try {
while (number != 1) {
condition.await();
}
number--;
System.out.println(Thread.currentThread().getName() + " " + number);
condition.signalAll();
} finally {
// TODO: handle finally clause
lock.unlock();
}
}
}
public class ProdConsumerDemo2 {
public static void main(String[] args) {
ShareData2 shareData = new ShareData2();
new Thread(() -> {
for (int i = 0; i {
for (int i = 0; i
A 1
B 0
A 1
B 0
A 1
B 0
A 1
B 0
A 1
B 0
A 1
B 0
A 1
B 0
A 1
B 0
A 1
B 0
A 1
B 0
class ShareData3 {
private int number = 1;
private Lock lock = new ReentrantLock();
private Condition c1 = lock.newCondition();
private Condition c2 = lock.newCondition();
private Condition c3 = lock.newCondition();
public void print5() throws Exception {
lock.lock();
try {
while (number != 1) {
c1.await();
}
number = 2;
for (int i = 0; i {
try {
for (int i = 0; i {
try {
for (int i = 0; i {
try {
for (int i = 0; i
上一篇:双指针算法
下一篇:如何理解Python中的装饰器?
文章标题:java线程之间通信,多种方式实现生产者消费者模式
文章链接:http://soscw.com/index.php/essay/76597.html