import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 共享资源类
*/
class ShareData {
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();
} finally {
lock.unlock();
}
}
public void deIncrement() throws Exception {
lock.lock();
try {
//判断
while (num == 0) {
//等待 不消费
condition.await();
}
//消费
num--;
System.out.println(Thread.currentThread().getName() + "\t" + num);
//通知唤醒
condition.signalAll();
} finally {
lock.unlock();
}
}
}
/**
* Description
* 一个初始值为0的变量 两个线程交替操作 一个加1 一个减1来5轮
*
* @author veliger@163.com
* @version 1.0
* @date 2019-04-13 14:01
**/
public class ProdConsumerTraditionDemo {
public static void main(String[] args) {
ShareData shareData = new ShareData();
new Thread(() -> {
for (int i = 1; i <= 5; i++) {
try {
shareData.increment();
} catch (Exception e) {
e.printStackTrace();
}
}
}, "AA").start();
new Thread(() -> {
for (int i = 1; i <= 5; i++) {
try {
shareData.deIncrement();
} catch (Exception e) {
e.printStackTrace();
}
}
}, "BB").start();
}
}
package cn.thread4;
/**
* 并发协作模型
* 生产者消费者实现方式之一
* 管程法
* 有缓冲容器,可以实现存量生产消费
* @author Chill Lyn
*
*/
public class PipelineMethod {
public static void main(String[] args) {
Buffer buffer = new Buffer();
new Thread(new Producer(007, buffer)).start();
new Thread(new Consumer(123, buffer)).start();
}
}
//生产者
class Producer implements Runnable {
int id;
Buffer buffer;
public Producer(int id, Buffer buffer) {
super();
this.id = id;
this.buffer = buffer;
}
@Override
public void run() {
for (int i = 1; i < 10; i++) {
buffer.set(new Data(i));
System.out.printf("产出第%d个数据\n", i);
}
}
}
//消费者
class Consumer implements Runnable {
int id;
Buffer buffer;
public Consumer(int id, Buffer buffer) {
super();
this.id = id;
this.buffer = buffer;
}
@Override
public void run() {
for (int i = 1; i < 10; i++) {
buffer.get();
System.out.printf("取出第%d个数据\n", i);
}
}
}
//缓冲区
class Buffer {
// 默认容量
Data[] data = new Data[10];
int count;
// 生产者存入
public synchronized void set(Data data) {
while (count == this.data.length) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.data[count++] = data;
this.notifyAll();
}
// 消费者取出
public synchronized Data get() {
while (count == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
return this.data[count--];
}
}
//数据
class Data {
int id;
public Data(int id) {
super();
this.id = id;
}
}
参考结果
信号灯法请见:Java_多线程_并发协作模型_生产者消费者模式_信号灯法