您的位置:首页 > 编程语言 > Java开发

生产者消费者问题

2016-07-27 11:38 405 查看
/**
* 生产者消费者
*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();
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 多线程