[英]Print odd and even with 2 threads get wrong
我想打印奇數,甚至從0到1000,簡單代碼如下,使用wait(),notifyAll()並同步以鎖定此實例。 但是結果停止打印0和1,對此我感到困惑,是否錯過了某些內容,或者同步關鍵字使用不正確? 有人可以解釋一下嗎,我試圖弄清楚幾個小時,卻一無所獲...
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();
}
}
結果是:
Even thread: 0
Odd thread: 1
並且JVM仍在運行,但是我要打印的是“ 0 1 2 3 4 5 ....”。 我不知道為什么錯了。
解決了,謝謝!!!
解釋:關鍵字“ this”應該指向一個特定的對象,我認為它指的是外部類實例。 我要做的只是創建一個名為obj的Object實例,並使用此“ obj”同步,等待,notifyAll。 只是一個參考問題。 我覺得我有點傻...
我發現我無法在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.