这是在其中,我希望得到如下输出一个消费者 - 生产者问题:
认沽:0
得到:0
认沽:1
得到:1
.. ..等等。
但与此形成对比的是,尽管使用了wait()和notify()方法,但Consumer类仍然多次使用相同的q值,并且生产者类超出了使用者的范围。我怎样才能获得同步输出?
同步实施:Java的
这是QFixed类:(定义把()和get()方法)
class QFixed{
int n;
boolean valueset = false;
synchronized int get(){
if(!valueset){
try {
wait();
} catch (InterruptedException ex) {
System.out.println("interrupted");
}
}
System.out.println("Got: " +n);
valueset = false;
notify();
return n;
}
synchronized void put(int n){
if (valueset){
try {
wait();
} catch (InterruptedException ex) {
System.out.println("interrupted");
}
}
this.n = n;
valueset = true;
System.out.println("Put: "+n);
notify();
}
}
这ProducerFixed类:
class ProducerFixed implements Runnable{
Q q;
Thread t;
public volatile boolean flag = true;
ProducerFixed(Q q){
this.q = q;
t = new Thread(this,"Producer");
t.start();
}
@Override
public void run(){
int i =0 ;
while(flag){
q.put(i++);
}
}
void stop() {
flag = false;
}
}
这ConsumerFixed类:
class ConsumerFixed implements Runnable{
Q q;
Thread t;
public volatile boolean flag = true;
ConsumerFixed(Q q){
this.q = q;
t = new Thread(this,"Consumer");
t.start();
}
@Override
public void run(){
while(flag){
q.get();
}
}
public void stop() {
flag = false;
}
}
这Producer_Consumer_Fixed类:
public class Producer_Consumer_Fixed {
public static void main(String arg[]){
Q q = new Q();
Producer p = new Producer(q);
Consumer c = new Consumer(q);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
System.out.println("interrupted");
}
p.stop();
c.stop();
try{
p.t.join();
c.t.join();
}catch(InterruptedException e){
System.out.println("interrupted");
}
}
}
请修正您的代码中的编译错误,您的代码似乎很好.. – TheLostMind 2014-12-19 11:16:11
如何解决编译错误? – 2014-12-19 11:28:18
您向我们展示的代码不能是您正在执行的代码。 '新Q()'< - 您提供的示例中没有名为'Q'的类。 – 2014-12-19 11:32:25