当前位置:网站首页>Producer and consumer issues
Producer and consumer issues
2022-06-22 06:17:00 【Kuxiaoya】
Producer and consumer issues Synchronzied edition
/** * Communication problems between threads : Producer and consumer issues ! * Threads execute alternately A B Operate on the same variable num = 0 * A num+1 * B num-1 */
public class A {
public static void main(String[] args) {
Data data = new Data();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"A").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"B").start();
}
}
// Judge wait , Business , notice
class Data{
// Numbers Resource class
private int number=0;
//+1
public synchronized void increment() throws InterruptedException {
if(number!=0){
// be equal to 0 when , work
// wait for
this.wait();
}
number++;
System.out.println(Thread.currentThread().getName()+"=>"+number);
// Notify other threads , I +1 It's over
this.notifyAll();
}
//-1
public synchronized void decrement() throws InterruptedException {
if(number==0){
// It's not equal to 0 when , work
// wait for
this.wait();
}
number--;
// Notify other threads , I -1 It's over
this.notifyAll();
}
}
The problem is ,A B C D 4 Threads ! spurious wakeup
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-ZhtqRxFK-1654847938784)(C:\Users\38492\AppData\Local\Temp\1654795628742.png)]](/img/d6/0fc281844f7f909595e6acf36e761a.png)
Solution : hold if Switch to while that will do !
/** * Communication problems between threads : Producer and consumer issues ! * Threads execute alternately A B Operate on the same variable num = 0 * A num+1 * B num-1 */
public class A {
public static void main(String[] args) {
Data data = new Data();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"A").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"B").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"C").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"D").start();
}
}
// Judge wait , Business , notice
class Data{
// Numbers Resource class
private int number=0;
//+1
public synchronized void increment() throws InterruptedException {
while(number!=0){
// be equal to 0 when , work
// wait for
this.wait();
}
number++;
System.out.println(Thread.currentThread().getName()+"=>"+number);
// Notify other threads , I +1 It's over
this.notifyAll();
}
//-1
public synchronized void decrement() throws InterruptedException {
while(number==0){
// It's not equal to 0 when , work
// wait for
this.wait();
}
number--;
System.out.println(Thread.currentThread().getName()+"=>"+number);
// Notify other threads , I -1 It's over
this.notifyAll();
}
}
JUC Producer of version
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-8wN0XQYe-1654848042391)(C:\Users\38492\AppData\Local\Temp\1654796413847.png)]](/img/a0/c36a46589413f2e9eaf7c782e198e9.png)
public class B {
/** * Communication problems between threads : Producer and consumer issues ! * Threads execute alternately A B Operate on the same variable num = 0 * A num+1 * B num-1 */
public static void main(String[] args) {
Data2 data = new Data2();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"A").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"B").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"C").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"D").start();
}
}
// Judge wait , Business , notice
class Data2{
// Numbers Resource class
private int number=0;
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
// condition.await(); // wait for
// condition.signalAll(); // Wake up all
//+1
public synchronized void increment() throws InterruptedException {
try {
lock.lock();// locked
// Business code
while(number!=0){
// be equal to 0 when , work
// wait for
condition.await();
}
number++;
System.out.println(Thread.currentThread().getName()+"=>"+number);
// Notify other threads , I +1 It's over
condition.signalAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();// Unlock
}
}
//-1
public void decrement() throws InterruptedException {
try {
lock.lock();// locked
// Business code
while(number==0){
// It's not equal to 0 when , work
// wait for
condition.await();
}
number--;
System.out.println(Thread.currentThread().getName()+"=>"+number);
// Notify other threads , I -1 It's over
condition.signalAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();// Unlock
}
}
}
Any new technology , It's not just about covering the original technology , Advantages and supplements !
Condition Precise notification and wake-up threads

How to solve random states ? Make it an orderly execution !
Code implementation :
public class C {
public static void main(String[] args) {
Data3 data = new Data3();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
data.printA();
}
}, "A").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
data.printB();
}
}, "B").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
data.printC();
}
}, "C").start();
}
}
class Data3 {
// Resource class Lock
private Lock lock = new ReentrantLock();
private Condition condition1 = lock.newCondition();
private Condition condition2 = lock.newCondition();
private Condition condition3 = lock.newCondition();
private int number = 1;//1A 2B 3C
public void printA() {
try {
lock.lock();// locked
// Business code : Judge -> perform -> notice
while (number != 1) {
// wait for
condition1.await();
}
System.out.println(Thread.currentThread().getName() + "=>AAA");
// Wake up the , Wake up the designated person ,B
number = 2;
condition2.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();// Unlock
}
}
public void printB() {
try {
lock.lock();// locked
// Business code : Judge -> perform -> notice
while (number != 2) {
// wait for
condition2.await();
}
System.out.println(Thread.currentThread().getName() + "->BBB");
// Wake up the , Wake up the designated person ,B
number = 3;
condition3.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();// Unlock
}
}
public void printC() {
try {
lock.lock();// locked
// Business code : Judge -> perform -> notice
while (number != 3) {
// wait for
condition3.await();
}
System.out.println(Thread.currentThread().getName() + "->CCC");
// Wake up the , Wake up the designated person ,C
number = 1;
condition1.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();// Unlock
}
}
}
Running results :

边栏推荐
猜你喜欢

MYSQL牛客刷题

动态创建对象执行方法

C#中的泛型

SQL injection vulnerability (XI) wide byte injection

leetcode每周3道(八)图之最短路

Research on dynamics and control of single ball robot

【CPU设计实战】数字逻辑电路设计基础(一)

matlab 的离散pid控制

【NAND文件系统】UBI介绍

Breakthrough in rich device platform: dayu200 based on rk3568 enters the openharmony 3.1 release trunk
随机推荐
You are using PIP version 19.0.3, however version 22.1.2 is available
相干声呐GeoSwath的综述
h = key.hashCode()) ^ (h >>> 16) 详细解读以及为什么要将hashCode值右移16位并且与原来的hashCode值进行异或操作
SQL injection vulnerability (XIV) XFF injection attack
SQL 注入漏洞(十)二次注入
五大常考SQL面试题
On the matrix order of MNIST linear model
Design input of Oracle project management system
小熊派BearPi-HM Micro正式合入OpenHarmony主干
【NAND文件系统】UBI介绍
ReadWriteLock
Discrete PID control based on MATLAB
Mail sending function is realized through SMTP protocol and exchange
SQL injection vulnerability (XIII) Base64 injection
单细胞论文记录(part14)--CoSTA: unsupervised convolutional neural network learning for ST analysis
Callable
Single cell paper records (part10) -- computational challenges and opportunities in SRT data
Information system project management - scope management (focus)
Single cell paper record (Part11) -- clustermap for multi-scale clustering analysis of spatial gene expression
纵向求最大最小与横向求最大最小greatest(),least(),max(),min()