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

java多线程--生产者和消费者模型

2016-01-12 12:28 477 查看
在开始我们先介绍wait和notifyAll这两个方法。这两个方法是Object类的方法,并且是native方法。

(1)调用某个对象的wait()方法能让当前线程阻塞,并且当前线程必须拥有此对象锁。

(2)调用notifyAll()方法能够唤醒所有正在等待这个对象的锁线程;只能唤醒等待该想拥有该对象锁的线程,因此我们需要保证对象的同一性。

生产者代码:

public Producer implements Runnable{
/**生产出来苹果剩余数量*/
public static int remainCount = 0;
/**总共生产的苹果数量*/
public static int pCount = 0;
/**苹果最大剩余量*/
public static int maxCount = 100;
/**对象锁*/
private Object obj = null;
public Producer(Object obj){
this.obj = obj;
}
private void producer(){
remainCount++;
System.out.println(Thread.currentTread() + ":正在生产第" + (++pCount) + "苹果");
}
public void run(){
while(true){
//同步代码块,持有obj对象锁
synchronized (obj) {
if (remainCount < pMaxCount) {
producer();
} else {
try {
obj.wait();
//不能唤醒自己,唤醒其他想持有该对象锁的线程
} catch (InterruptedException e) {
e.printStackTrace();
}
}
obj.notifyAll();
}
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}


消费者

public class Consumer implements Runnable {
/**消费苹果的数量*/
public static int cCount = 0;
private Object obj;
public Consumer(Object obj) {
this.obj = obj;
}
@Override
public void run() {
while (true) {
//与生产者要持有相同的对象
synchronized (obj) {
if (Producer.remainCount > 0) {
consumer();
} else {
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
obj.notifyAll();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void consumer() {
Producer.remainCount--;
System.out.println(Thread.currentThread() + ":正在消费第" + (++cCount) + "个苹果");
}
}


主函数

public class Main {
public static void main(String[] args) {
new Main().proAndcon();
}
private void proAndcon() {
Object obj = new Object(); //生产者和消费者要持有的对象
Thread tP1 = new Thread(new Producer(obj));
tP1.start();
Thread tP2 = new Thread(new Producer(obj));
tP2.start();
Thread tC1 = new Thread(new Consumer(obj));
tC1.start();
Thread tC2 = new Thread(new Consumer(obj));
tC2.start();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: