黑马程序员技术交流社区
标题:
帮忙看下这个多线程程序哪里错了?
[打印本页]
作者:
jojo
时间:
2015-1-16 00:47
标题:
帮忙看下这个多线程程序哪里错了?
程序是想实现,多个生产者,多个消费者,资源有多个(通俗来讲,仓库中可以存放多个产品,以往的程序只是一个),程序如下,实在不知道哪里错了。求高手解答!
package com.bocsoft.study;
import java.util.ArrayList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ProduceConsume {
public static void main(String[] args) {
Resource r = new Resource();
Produce p1 = new Produce(r,"苹果");
Produce p2 = new Produce(r,"香蕉");
Produce p3 = new Produce(r,"橘子");
Consume c = new Consume(r);
Thread t1 = new Thread(p1,"苹果生产者");
Thread t2 = new Thread(p2,"香蕉生产者");
Thread t3 = new Thread(p3,"橘子生产者");
Thread t4 = new Thread(c,"消费者1号");
Thread t5 = new Thread(c,"消费者2号");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
class Resource {
ArrayList<Food> al = new ArrayList<Food>();// 仓库中可以存放多个产品
int max = 5;// 定义最多存放的产品数量
Lock lock = new ReentrantLock();// 创建锁对象
Condition p_condition = lock.newCondition();// 生产者使用的Condition
Condition c_condition = lock.newCondition();// 消费者使用的Condition
void put(Food food) {
lock.lock();// 获取锁
try {
while (!(al.size() < max))
// 若资源已满则等待消费者消费
try {
p_condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
// 未满则生产产品
al.add(food);// 将产品添加进产品库
System.out.println(Thread.currentThread().getName() + "生产了产品:----------" + food);
c_condition.signal();// 唤醒消费者消费
} finally {
lock.unlock();// 如遇异常,锁必须释放
}
}
void get() {
lock.lock();// 获取锁
try {
while (al.size() == 0)//若无资源消费则等待
try {
c_condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
Food food = al.remove(0);//消费一个产品,这里为了方便起见,每个消费者都消费数组中的第一个元素
System.out.println(Thread.currentThread().getName() + "消费了产品:----------" + food);
p_condition.signal();
} finally {
lock.unlock();// 如遇异常,锁必须释放
}
}
}
class Produce implements Runnable {
Resource r;
String name;//生产的产品的名称
Produce(Resource r,String name) {
this.r = r;
this.name = name;
}
public void run() {
Food food = new Food(name);
r.put(food);
}
}
class Consume implements Runnable {
Resource r;
Consume(Resource r) {
this.r = r;
}
public void run() {
r.get();
}
}
class Food {
String name;
Food(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
复制代码
作者:
kerner
时间:
2015-1-16 10:27
public void run() {
while(true)
r.get();
}
public void run() {
Food food = new Food(name);
while(true)
r.put(food);
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2