我创建了一个类 UnSafeTask:
package com.threads;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class UnsafeTask implements Runnable {
private Date startDate;
@Override
public void run() {
startDate = new Date();
System.out.printf("Starting Thread: %s : %s\n", Thread.currentThread().getId(), startDate);
try {
TimeUnit.SECONDS.sleep((int) Math.rint(Math.random() * 10));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("Thread Finished: %s : %s\n", Thread.currentThread().getId(), startDate);
}
}
我在一个核心类中使用它,如下所示:
package com.threads;
import java.util.concurrent.TimeUnit;
public class Core {
public static void main(String[] args) {
UnsafeTask task = new UnsafeTask();
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(task);
thread.start();
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
结果与预期一致(变量由线程共享)。当我按如下方式重构 Core 以使用匿名可运行类时:
package com.threads;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class Core {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(new Runnable() {
Date startDate = new Date();
@Override
public void run() {
startDate = new Date();
System.out.printf("Starting Thread: %s : %s\n", Thread.currentThread().getId(), startDate);
try {
TimeUnit.SECONDS.sleep((int) Math.rint(Math.random() * 10));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("Thread Finished: %s : %s\n", Thread.currentThread().getId(), startDate);
}
});
thread.start();
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
现在变量 (startDate) 是线程安全的。为什么在这种情况下变量线程是安全的?提前致谢。