Java多線程與併發_Synchronized和Lock實現生產者消費者模式
能自己扛,就別聲張
一、生產者消費者例子
現在兩個線程
可以操作初始值爲零的一個變量,
實現一個線程對該變量加1,一個線程對該變量減1
交替,來10輪,變量初始值爲零
二、Synchronized實現
/**
* @Author: slx
* @Date: 2019/4/24 19:09
*/
public class NotifyWaitDemoReview {
public static void main(String[] args) {
//線程操縱資源類
ShareData shareData = new ShareData();
//生產者
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
shareData.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"AA").start();
//消費者
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
shareData.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"BB").start();
}
}
class ShareData {
private int number = 0;
public synchronized void increment() throws InterruptedException {
//1.判斷
while (number != 0) {
this.wait();
}
//2.幹活
++number;
System.out.println(Thread.currentThread().getName() + "\t" + number);
//3.通知
this.notifyAll();
}
public synchronized void decrement() throws InterruptedException {
//1.判斷
while (number == 0) {
this.wait();
}
//2.幹活
--number;
System.out.println(Thread.currentThread().getName() + "\t" + number);
//3.通知
this.notifyAll();
}
}
三、Lock實現
class ShareData {
private int number = 0;
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void increment() throws InterruptedException {
lock.lock();
try {
//1.判斷
while (number != 0) {
// this.wait();
condition.await();
}
//2.幹活
++number;
System.out.println(Thread.currentThread().getName() + "\t" + number);
//3.通知
// this.notifyAll();
condition.signalAll();
}catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void decrement() throws InterruptedException {
lock.lock();
try {
//1.判斷
while (number == 0) {
// this.wait();
condition.await();
}
//2.幹活
--number;
System.out.println(Thread.currentThread().getName() + "\t" + number);
//3.通知
// this.notifyAll();
condition.signalAll();
}catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
四、結果
AA 1
BB 0
AA 1
BB 0
AA 1
BB 0
AA 1
BB 0
AA 1
BB 0
AA 1
BB 0
AA 1
BB 0
AA 1
BB 0
AA 1
BB 0
AA 1
BB 0
Process finished with exit code 0