基本上以下的作品,但自从我读了关于最后的关键字我不知道了,如果我不得不声明名称最终如果不同的线程访问它?从内部类的线程访问外部字段(非最终)是否是线程安全的?
在此先感谢。
public class Test4 {
// to ensure thread-safety do we have to declare the variable name final ?
private String name;
public Test4 (String name) {
this.name = name;
}
public void start() {
new MyThread().start();
}
private class MyThread extends Thread {
public void run() {
System.out.println(name);
}
}
public static void main(String[] args) {
Test4 t = new Test4("Don't know if I am threadsafe");
t.start();
}
}
这将永远打印“不知道我是否是线程安全的”,无论最终如何。在构造对象之前,new()不会返回;这将在新线程启动之前发生。 – tucuxi
@pst在进一步写入'name'的情况下,是的,有差异。但是,如果写'唯一时间'是在施工期间,那么'最终'是不需要的(尽管它确实使读者更清楚)。 – tucuxi