黑马程序员技术交流社区
标题:
这是哪里错了啊,已经看了半个小时了!!求帮助!
[打印本页]
作者:
Rainbow
时间:
2013-7-19 23:09
标题:
这是哪里错了啊,已经看了半个小时了!!求帮助!
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ProducerConcumer {
public static void main(String[] args) {
Res res = new Res();
Producer pro = new Producer(res);
Concumer con = new Concumer(res);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(pro);
Thread t3 = new Thread(con);
Thread t4 = new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Res {
private String name;
private int count = 1;
boolean flag = false;
private Lock lock = new ReentrantLock();
Condition condition_pro = lock.newCondition();
Condition condition_con = lock.newCondition();
public void set(String name) throws InterruptedException {
lock.lock();
try {
while (flag) {
condition_pro.await();
}
this.name = name + "..." + count++;
System.out.println(Thread.currentThread().getName() + "生产者"
+ this.name);
flag = true;
condition_con.signal();
} finally {
lock.unlock();
}
}
public void out() throws InterruptedException {
lock.lock();
try {
while (!flag) {
condition_con.await();
}
System.out.println(Thread.currentThread().getName() + "......."
+ this.name);
flag = false;
condition_pro.signal();
} finally {
lock.unlock();
}
}
}
class Producer implements Runnable {
private Res res;
public Producer(Res res) {
this.res = res;
}
public void run() {
// TODO Auto-generated method stub
try {
res.set("");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Concumer implements Runnable {
private Res res;
public Concumer(Res res) {
this.res = res;
}
public void run() {
// TODO Auto-generated method stub
try {
res.out();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
复制代码
作者:
刘张朋
时间:
2013-7-19 23:28
你的代码没问题啊,每个线程任务都可以执行一次,你是不是觉得不能像视频里那样生产很多啊?如果是的话原因就是你在生产消费时都没加循环
作者:
Rainbow
时间:
2013-7-20 13:21
刘张朋 发表于 2013-7-19 23:28
你的代码没问题啊,每个线程任务都可以执行一次,你是不是觉得不能像视频里那样生产很多啊?如果是的话原因 ...
哦哦,是啊,就是出来四个。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2