0
我使用爲了執行第一個線程,然後在第一個線程完成時執行另一個線程,但是兩個線程同時執行。爲什麼?當我使用'synchronized'時,爲什麼我的線程不會一個接一個地執行?
public class PrintNums extends Thread {
int num;
public PrintNums(int x) {
this.num = x;
}
@Override
public void run() {
this.count();
}
public synchronized void count() {
for (int i = 1; i <= 5; i++) {
System.out.println((2 * i - this.num));
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException ex) {
}
}
}
public static void main(String[] args) {
PrintNums odd = new PrintNums(1);
PrintNums even = new PrintNums(0);
odd.start();
even.start();
}
}
同步用於訪問特定對象(即,同步到一個對象)。你有兩個不同的對象('odd'和'even')。 –
[爲什麼這種同步方法不能按預期工作?](http://stackoverflow.com/q/26610791) – Tom