我想了解一个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