[英]Print odd and even with 2 threads get wrong
I want to print odd and even from 0 to 1000, the simple code are as follow using wait(),notifyAll() and synchronized to lock this instance. 我想打印奇数,甚至从0到1000,简单代码如下,使用wait(),notifyAll()并同步以锁定此实例。 But the result stops printing 0 and 1, I am confused by this, did I miss something or the synchronized key-word isn't used proper?
但是结果停止打印0和1,对此我感到困惑,是否错过了某些内容,或者同步关键字使用不正确? Can someone explain this, I've trying to figure it out for several hours,yet get nothing...
有人可以解释一下吗,我试图弄清楚几个小时,却一无所获...
public class Main {
public static void main(String[] args) {
final int count = 1000;
new Thread() {
public void run() {
for (int j = 0; j <= count; j = j + 2) {
synchronized (this) {
System.out.println("Even thread:\t" + j);
notifyAll();
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}.start();
new Thread() {
public void run() {
for (int j = 1; j <= count; j = j + 2)
synchronized (this) {
System.out.println("Odd thread:\t" + j);
notifyAll();
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
}
The result is: 结果是:
Even thread: 0
Odd thread: 1
and the JVM is still running,But I want to print is "0 1 2 3 4 5....". 并且JVM仍在运行,但是我要打印的是“ 0 1 2 3 4 5 ....”。 I don't know why it's wrong.
我不知道为什么错了。
Solved ,thank you!!! 解决了,谢谢!!!
Explain: And key-word "this" should refer to a specific object, I thought it refers to the outer class instance for granted. 解释:关键字“ this”应该指向一个特定的对象,我认为它指的是外部类实例。 And what I do is just create a Object instance called obj , and synchronized,wait, notifyAll with this "obj".
我要做的只是创建一个名为obj的Object实例,并使用此“ obj”同步,等待,notifyAll。 Just a problem of reference.
只是一个参考问题。 I feel I am a little dumb...
我觉得我有点傻...
I found I can't accept my answer within 2 days:"accept × You can accept your own answer in 2 days" 我发现我无法在2天内接受答案:“接受×您可以在2天内接受自己的回答”
public class Main {
public static void main(String[] args) {
//String obj="";
Object obj=new Object();
final int count = 1000;
new Thread() {
public void run() {
for (int j = 0; j <= count; j = j + 2) {
synchronized (obj) {
System.out.println("Even thread:\t" + j);
if(j==1000) System.exit(0);//exit the JVM when prints 1000
obj.notifyAll();
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}.start();
new Thread() {
public void run() {
for (int j = 1; j <= count; j = j + 2)
synchronized (obj) {
System.out.println("Odd thread:\t" + j);
obj.notifyAll();
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.