class Q {
int n;
boolean valueset = false; synchronized int get() {
if (!valueset)
try {
wait();
} catch (InterruptedException e) {
}//else{
System.out.println("got:" + n);
valueset = false;
notify();
//}
return n;
} synchronized void put(int n) {
if (valueset)
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}//else{
this.n = n;
valueset = true;
System.out.println("put: " + n);
notify();
//}
}
}class Producer implements Runnable {
Q q; Producer(Q q) {
this.q = q;
new Thread(this, "producer").start();
} public void run() {
// TODO Auto-generated method stub
int i = 0;
while (true) {
q.put(i++);
}
}}class Consumer implements Runnable {
Q q; Consumer(Q q) {
this.q = q;
new Thread(this, "consumer").start();
} public void run() {
// TODO Auto-generated method stub
while (true) {
q.get();
}
}}public class PC { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("press Control c to stop");
}}
在Q中去掉//和不去掉//有何区别!为什么运行结果不一样?
int n;
boolean valueset = false; synchronized int get() {
if (!valueset)
try {
wait();
} catch (InterruptedException e) {
}//else{
System.out.println("got:" + n);
valueset = false;
notify();
//}
return n;
} synchronized void put(int n) {
if (valueset)
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}//else{
this.n = n;
valueset = true;
System.out.println("put: " + n);
notify();
//}
}
}class Producer implements Runnable {
Q q; Producer(Q q) {
this.q = q;
new Thread(this, "producer").start();
} public void run() {
// TODO Auto-generated method stub
int i = 0;
while (true) {
q.put(i++);
}
}}class Consumer implements Runnable {
Q q; Consumer(Q q) {
this.q = q;
new Thread(this, "consumer").start();
} public void run() {
// TODO Auto-generated method stub
while (true) {
q.get();
}
}}public class PC { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("press Control c to stop");
}}
在Q中去掉//和不去掉//有何区别!为什么运行结果不一样?
假如valueset为false,则进入if,而且当wait()结束后会直接跳到else{}的后面,不会执行else{}内部的代码。也就是说只有当valueset为true时else{}中的代码才会被执行不去掉//时:
无论valueset为什么值都会执行if{}之后的代码。所以两种结果当然会不同。这是逻辑问题,并不是线程问题