Developing Games in Java 裡不好的 Thread 例子

翻了一下這本書 Developing Games in Java

在第一章看到像這樣的程式

public class MyClass extends SomeOtherClass implements Runnable {

public MyClass() {

Thread thread = new Thread(this);

thread.start();

}

public void run() {

System.out.println("Do something cool here.");

}

}

作者可能沒看過 Safe construction techniques 這篇文章

因為在 constructor 裡傳 this 給新 thread 並讓它開始執行

可能會使物件在還沒完全建構好前就被新 thread 用到,是應該避免的寫法

我沒有說這本書不好的意思,因為才看了一點點而已。只是提醒自己像這樣的地方要留意,不要看書上有這麼寫,就跟著寫。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *