/
SafeTask.java
36 lines (31 loc) · 1011 Bytes
/
SafeTask.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.diguage.books.concurrencycookbook.chapter1.recipe9;
import java.util.Date;
import java.util.concurrent.TimeUnit;
/**
* 使用线程本地变量保证线程安全
* <p/>
* Coder: D瓜哥,http://www.diguage.com/
* Date: 2013-09-29
* Time: 23:34
*/
public class SafeTask implements Runnable {
private static ThreadLocal<Date> startDate = new
ThreadLocal<Date>() {
@Override
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());
}
}