我想了解一個Thread對象狀態的線程完成後後。我讀過一本書,一旦線程完成其run()方法,線程對象仍然是頭上的有效對象,仍然可以用作實例對象,您仍然可以調用它的方法。我決定嘗試以下示例:運行線程的run()方法的線程已經完成
class DieThread implements Runnable{
int y = 0;
public void run(){
for(int x=0; x<100; x++){
System.out.println(" " + Thread.currentThread().getName());
System.out.println("y is " + y);
y++;
System.out.println("y is " + y);
}
}
}
class ZiggyTest2{
public static void main(String[] args){
DieThread d = new DieThread();
Thread a = new Thread(d);
Thread b = new Thread(d);
Thread c = new Thread(d);
a.start();
b.start();
c.start();
try{
a.join();
b.join();
c.join();
}catch(Exception e){
System.out.println(e);
}
System.out.println("Running C's Run");
c.run();
}
}
main()通過使用join()等待其他3個線程完成。然後調用c的run()方法,但由於某種原因,它不會從run()方法中打印任何內容。這是我運行上述程序後輸出的最後幾行。
y is 287
y is 287
y is 288
y is 289
Thread-1
Thread-0
y is 289
y is 289
y is 290
y is 291
Thread-1
Thread-0
y is 291
y is 291
y is 292
y is 293
Thread-1
Thread-0
y is 293
y is 293
y is 294
y is 295
Thread-0
y is 295
y is 296
Thread-0
y is 296
y is 297
Thread-0
y is 297
y is 298
Thread-0
y is 298
y is 299
Thread-0
y is 299
y is 300
Running C's Run
即使線程已經完成,我期待y因爲c.run()調用的值爲400。
任何想法?
謝謝
你確定你不想叫d.run()?此外,我很驚訝沒有破壞,因爲你有3個線程遞增相同的變量,沒有鎖定。 – Thomas
是的,我想在完成後運行線程對象。 – ziggy