非线程安全
public class UnSafeThreadLocalDemo {
private int count = 0;
public static void main(String[] args) {
UnSafeThreadLocalDemo unSafeThreadLocalDemo = new UnSafeThreadLocalDemo();
for (int i = 0; i < 5; i++) {
int finalI = i;
new Thread(new Runnable() {
@Override
public void run() {
unSafeThreadLocalDemo.process();
unSafeThreadLocalDemo.print(finalI);
}
}).start();
}
}
public void process() {
for (int i = 0; i < 10; i++) {
count += 1;
try {
TimeUnit.MILLISECONDS.sleep(new Random().nextInt(10) + 10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void print(int i) {
System.out.println("count(" + i + ") = " + count);
}
}
输出:
count(1) = 44
count(0) = 46
count(3) = 47
count(2) = 49
count(4) = 49
线程安全
public class SafeThreadLocalDemo {
// private int count = 0;
private ThreadLocal<Integer> count = new ThreadLocal<Integer>() {
protected Integer initialValue() {
return 0;
}
};
public void process() {
for (int i = 0; i < 10; i++) {
count.set(count.get() + 1);
try {
TimeUnit.MILLISECONDS.sleep(new Random().nextInt(10) + 10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void print(int i) {
System.out.println("count(" + i + ") = " + count.get());
}
public static void main(String[] args) {
SafeThreadLocalDemo safeThreadLocalDemo = new SafeThreadLocalDemo();
for (int i = 0; i < 5; i++) {
int finalI = i;
new Thread(new Runnable() {
@Override
public void run() {
safeThreadLocalDemo.process();
safeThreadLocalDemo.print(finalI);
}
}).start();
}
}
}
输出:
count(1) = 10
count(0) = 10
count(2) = 10
count(4) = 10
count(3) = 10