本帖最后由 陈志强 于 2013-3-15 00:19 编辑
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ProducerConsumerDemo2 {
public static void main(String[] args) {
Resouce res=new Resouce();
Producer pro=new Producer(res);
Consumer con=new Consumer(res);
Thread t1=new Thread(pro);
Thread t2=new Thread(con);
t1.start();
t2.start();
}
}
class Resouce{
private String name;
private int count=1;
private boolean flag=false;
private Lock lock=new ReentrantLock();
private Condition condition=lock.newCondition();
public void set(String name) throws InterruptedException{
lock.lock();
try{
if(flag)
condition.await();
this.name=name;
System.out.println(Thread.currentThread().getName()+"......生产者......"+this.name);
flag=true;
condition.signal();
}finally{
lock.unlock();
}
}
public void out() throws InterruptedException{
lock.lock();
try{
if(!flag)
condition.await();
this.name=name+".."+count++;
System.out.println(Thread.currentThread().getName()+"......消费者....................."+this.name);
flag=false;
condition.signal();
}finally{
lock.unlock();
}
}
}
class Producer implements Runnable{
private Resouce res;
Producer(Resouce res){
this.res=res;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
try {
res.set("++商品++");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable {
private Resouce res;
Consumer(Resouce res){
this.res = res;
}
public void run(){
while(true){
try {
res.out();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Exception in thread "main" java.lang.NoSuchMethodError: Consumer.<init>(LResouce;)V
at ProducerConsumerDemo2.main(ProducerConsumerDemo2.java:14)
这代码是在eciplice上编写的,当然小弟是新手,是毕老师day12 视频的代码,可是却报错了,在Editplus却能编译通过甚至运行,这是为啥?
抱歉,只有手机能联网,不要见怪啊,麻烦大神说明下,谢谢了 |
|