public class Thread_04_ProducerConsumer {
public static void main(String[] args) {
SynStack ss = new SynStack();
Thread t1 = new Thread(new Producer(ss));
Thread t2 = new Thread(new Consumer(ss));
t1.start();
t2.start();
}
}
class Producer implements Runnable{
private SynStack ss = null;
public Producer(SynStack ss) {
super();
this.ss = ss;
}
@Override
public void run() {
for (int i = 0; i < 26; i++) {
ss.push((char)('a'+i));
}
}
}
class Consumer implements Runnable{
private SynStack ss = null;
public Consumer(SynStack ss) {
super();
this.ss = ss;
}
@Override
public void run() {
for (int i = 0; i < 26; i++) {
try {
Thread.sleep(1010);
} catch (InterruptedException e) {
e.printStackTrace();
}
ss.pop();
}
}
}
class SynStack{
// 缓冲区
private char[] data = new char[6];
// 已有元素个数
private int count = 0;
public synchronized void push(char ch){
// 唤醒消费
this.notifyAll();
// 判断是否生产满了
if (count == data.length) {
// 满了就不生产了
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
data[count] = ch;
count++;
System.out.println("生产了:"+ch+",容器中有:"+count+"个元素");
}
public synchronized char pop(){
this.notifyAll();
char ch ;
// 判断是否还有元素
if (count == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count--;
ch = data[count];
System.out.println("消费了:"+ch+",容器中有:"+count+"个元素");
return ch;
}
}
java线程生产者消费者
最新推荐文章于 2024-08-23 00:00:00 发布