題目 現在有生產者消費者兩個線程 可以對初始值爲0的一個變量進行操作
實現生產者線程對該變量加1 消費者線程立刻對該變量減1
實現交替 來10輪 (我們要求生產1個後 馬上就進行消費)(消費一個後 就馬上進行生產)
注意 生產者加1之後 消費者立馬減1 結果應該是 1 0 1 0 1 0 …
傳統版
package com.zyk;
//資源類
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.notify();
}
//消費者
public synchronized void decrement() throws InterruptedException {
//1 判斷
while(number==0){
this.wait();
}
//2 幹活
number--;
System.out.println(Thread.currentThread().getName()+"\t"+number);
//3 通知
this.notify();
}
}
public class Product_ConsumerDemo1 {
public static void main(String[] args) {
ShareData shareData=new ShareData();
for (int i = 1; i <=10 ; i++) {
new Thread(()->{
try {
shareData.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
},"生產者").start();
}
for (int i = 1; i <=10 ; i++) {
new Thread(()->{
try {
shareData.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
},"消費者").start();
}
}
}
Lock版
package com.zyk;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class MyShare{
private int num=0;
private Lock lock=new ReentrantLock();
private Condition condition=lock.newCondition();
public void increment()throws Exception{
lock.lock();
try {
//判斷
while (num!=0){
condition.await();
}
//幹活
num++;
System.out.println(Thread.currentThread().getName()+"\t 生產了"+num);
//通知
condition.signalAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void decrement()throws Exception{
lock.lock();
try {
//判斷
while (num==0){
condition.await();
}
//幹活
num--;
System.out.println(Thread.currentThread().getName()+"\t 消費了"+num);
//通知
condition.signalAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
public class Product_ConsumerDemo2 {
public static void main(String[] args) {
MyShare myShare=new MyShare();
new Thread(()->{
for (int i = 0; i <10 ; i++) {
try {
myShare.increment();
} catch (Exception e) {
e.printStackTrace();
}
}
},"AAA").start();
new Thread(()->{
for (int i = 0; i <10 ; i++) {
try {
myShare.decrement();
} catch (Exception e) {
e.printStackTrace();
}
}
},"BBB").start();
}
}