多线程中的生产者消费者问题(一)
写一个简单的多线程的生产者消费者问题,练手。第一版比较简陋,后面改进。
package mxf.study.java.thread;
/**
* 多线程的生产者和消费者问题。
* 使用 synchronized 版本
*/
public class ThreadSync {
private static final int size = 10;
public static void main(String[] args) throws InterruptedException {
final MyBag bag = new MyBag(); //同一个锁对象
Thread writerThread = new Thread(new Runnable() {
@Override
public void run() {
while(bag.count < size){
synchronized (bag) {
if(bag.flag){ //有货了就wait
try {
bag.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
bag.count = bag.count + 1;
System.out.println("writer:" + bag.count);
bag.flag = true;
// test.notify();
bag.notifyAll();
}
}
}
});
Thread readerThread = new Thread(new Runnable() {
@Override
public void run() {
while(bag.count < size){
synchronized (bag) {
if(!bag.flag){ //没货了wait
try {
bag.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("reader:" + bag.count);
bag.flag = false;
// test.notify();
bag.notifyAll();//唤醒同一个锁的其他线程
}
}
}
});
writerThread.start();
readerThread.start();
writerThread.join();
readerThread.join();
}
}
class MyBag{
int count = 0; //货品编号
boolean flag = false; //标记,是否有货
}
浙公网安备 33010602011771号