rt.jar包里有个SafeThread类,类源码如下:
final class SafeThread extends Thread {
private volatile boolean ran = false;
public SafeThread(Runnable target) {
super(target);
}
public final void run() {
if (Thread.currentThread() != this) {
throw new IllegalStateException("The run() method in a"
+ " SafeThread cannot be called from another thread.");
}
synchronized (this) {
if (!ran) {
ran = true;
}
else {
throw new IllegalStateException("The run() method in a"
+ " SafeThread cannot be called more than once.");
}
}
super.run();
}
}
为什么加了synchronized
之后,还需要给ran变量加volatile
呢,如果单例模式的双检查是为了防止指令重排,但这里初始状态就已经赋值了,应该不会存在指令重排的情况了吧