run()
私たちが知っているように、メソッドを使用して複数のスレッドがメソッドを呼び出すのを防ぐための規定はありませんstart()
。2 つのオブジェクトm1
を作成し、m2
両方とも同じスレッドを呼び出して実行しました。
m1.start
2 番目のオブジェクトの実行が開始される前に、スレッドを呼び出して、最初のオブジェクトの実行が終了 () されていることを確認する必要があります。
私の質問は、私が作成したスレッド (つまり)でメソッドでsynchronized
キーワードを使用できないのはなぜですか?run()
MyThread1
作成したスレッドでrun()メソッドに「同期」を使用しようとしましたが、任意の出力が得られます(つまり、実行が完了m2
するのを待ちません)。m1
プログラムの一番下に、私が取得している出力が表示されます。
public class ExtendedThreadDemo {
public static void main(String[] args) {
Mythread1 m1 =new Mythread1();
Mythread1 m2 =new Mythread1();
m1.start();
m2.start();
System.out.println(" main thread exiting ....");
}
}
マイスレッド
public class MyThread1 extends Thread {
public synchronized void run() {
for(int i=1; i<5; i++) {
System.out.println(" inside the mythread-1 i = "+ i);
System.out.println(" finish ");
if (i%2 == 0) {
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
System.out.println(" the thread has been interrupted ");
}
}
}
}
}
出力
main thread exiting ....
inside the mythread-1 i = 1
finish
inside the mythread-1 i = 2
finish
inside the mythread-1 i = 1
finish
inside the mythread-1 i = 2
finish
inside the mythread-1 i = 3
finish
inside the mythread-1 i = 4
finish
inside the mythread-1 i = 3
finish
inside the mythread-1 i = 4
finish
の後でわかるようにi = 2
、2 番目のオブジェクト (つまりm2.start()
) が実行を開始しました。