https://www.cnblogs.com/dolphin0520/p/3920407.html
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);
}
}第一种,同一个Runnable对象时
public class Core {
public static void main(String[] args) {
UnsafeTask task=new UnsafeTask();
for (int i=0; i<10; i++){
// UnsafeTask task=new UnsafeTask();
Thread thread=new Thread(task);
thread.start();
try { TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}你会发现Thread Finished:的时间是相同的。
public static void main(String[] args) {
// UnsafeTask task=new UnsafeTask();
for (int i=0; i<10; i++){
UnsafeTask task=new UnsafeTask();
Thread thread=new Thread(task);
thread.start();
try { TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}此种情况每次都是新创建的Runnable对象,不存在上面的问题。使用Threadlocal的方式
public class UnsafeTask implements Runnable {
// private Date startDate;
private static ThreadLocal<Date> startDate = new ThreadLocal<Date>() {
protected Date initialValue() {
return new Date();
}
};
@Override
public void run() {
System.out.printf("Starting Thread: %s : %s\n", Thread.currentThread().getId(), startDate.get());
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.get());
}
}1
10万+

被折叠的 条评论
为什么被折叠?



