0
私はを使って最初のスレッドを実行し、最初のスレッドが終了したときにもう1つのスレッドを実行しますが、両方のスレッドが同時に実行されます。どうして?明確な目標なし私は '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();
}
}
同期は、特定のオブジェクトへのアクセス(つまり、1つのオブジェクトへの同期)です。 2つの異なるオブジェクト( 'odd'と' even')があります。 –
[この同期化されたメソッドが期待どおりに機能しないのはなぜですか?](0120-13753) – Tom