黑马程序员技术交流社区
标题:
异常的问题
[打印本页]
作者:
顾传文
时间:
2013-3-7 12:00
标题:
异常的问题
package com.itheima;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Resource{
private String name;
private int count = 1;
private boolean flag = false;
private Lock lock = new ReentrantLock();
private Condition condition_pro = lock.newCondition();
private Condition condition_con = lock.newCondition();
public void set(String name) throws InterruptedException{
lock.lock();
try{
while(flag){
condition_pro.wait();
}
System.out.println("生产者"+name+count);
this.name = name+"_"+count++;
flag = true;
condition_con.signal();
}finally{
lock.unlock();
}
}
public void get() throws InterruptedException{
lock.lock();
try{
while(!flag){
condition_con.wait();
}
System.out.println("消费者"+"-------------------"+name);
flag = false;
condition_pro.signal();
}finally{
lock.unlock();
}
}
}
class Producer implements Runnable{
private Resource rs;
public Producer(Resource rs){
this.rs = rs;
}
@Override
public void run() {
while(true){
try {
rs.set("产品");
} catch (InterruptedException e) {
//e.printStackTrace();
}
}
}
}
class Consumer implements Runnable{
private Resource rs;
public Consumer(Resource rs){
this.rs = rs;
}
@Override
public void run() {
while(true){
try {
rs.get();
} catch (InterruptedException e) {
//e.printStackTrace();
}
}
}
}
public class ProducerConsumer {
public static void main(String[] args) {
Resource resource = new Resource();
new Thread(new Producer(resource)).start();
new Thread(new Consumer(resource)).start();
new Thread(new Producer(resource)).start();
new Thread(new Consumer(resource)).start();
}
}
运行时报异常,怎么解决?
作者:
BitmapFactory
时间:
2013-3-7 12:10
condition_con.await();
condition调用的是await()
try{
while(flag){
condition_pro.wait();
//这个地方 }
System.out.println("生产者"+name+count);
this.name = name+"_"+count++;
flag = true;
condition_con.signal();
}finally{
lock.unlock();
}
try{
while(!flag){
condition_con.wait();
//这个地方 }
System.out.println("消费者"+"-------------------"+name);
flag = false;
condition_pro.signal();
}finally{
lock.unlock();
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2