/**
* 生产者消费者
*1.共享数据的不一致/临界资源的保护
*2.java对象锁的概念
*3.synchronized关键字wait()机notify()方法的结合
*/
public class ProducerConsumer {
public static void main(String[] args){
SyncStack stack = new SyncStack();
Thread p1 = new Thread(new Producer(stack));
Thread c1 = new Thread(new Consumer(stack));
p1.start();
c1.start();
}
}
// 支持多线程同步操作的堆栈的实现
class SyncStack {
private int index = 0;
private char[] data = new char[6];
public synchronized void push(char c) {
if (index == data.length) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
data[index] = c;
index++;
}
public synchronized char pop(){
if(index == 0) {
try {
this.wait();
} catch(InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
index --;
return data[index];
}
}
// 生产者
class Producer implements Runnable {
SyncStack stack;
public producer(SyncStack stack) {
this.stack = stack;
}
@Override
public void run() {
for(int i = 0; i < 20; i ++) {
char c = (char) (Math.random() * 26 + 'A');
stack.push(c);
System.out.println("生产:" + c);
try {
Thread.sleep((long) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// 消费者
class Consumer implements Runnable {
SyncStack stack;
public Consumer(SyncStack stack) {
this.stack = stack;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
char c = stack.pop();
System.out.println("消费:" + c);
try {
Thread.sleep((long) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
生产者消费者问题
最新推荐文章于 2023-04-26 09:27:27 发布