ThreadLocal同步机制实例比较
package com.lovo;
public class ThreadLocalDemo implements Runnable {
private int counter;//计时器
//在ThreadLocal中存放一个计数器本地变量
private static ThreadLocal<Integer> localCounter = new ThreadLocal<Integer>(){
//通过匿名内部类重写initiaValue方法,指定初始值
protected Integer initialValue(){
return 0;
}
};
public ThreadLocalDemo(){
counter = 0;
Thread thread1 = new Thread(this);
Thread thread2 = new Thread(this);
Thread thread3 = new Thread(this);
//启动线程
thread1.start();
thread2.start();
thread3.start();
}
//获取计数器的值
public int getCounter(){
return counter;
}
//计数器加一
public void addCounter(){
synchronized (localCounter) {
counter = counter +1;
}
}
//获取本地计数器的值
public int getLocalCounter(){
return localCounter.get();
}
//本地计数器加一
public void addLocalCounter(){
localCounter.set(localCounter.get()+1);
}
//显示计数器和本地计数器值
public void display(){
System.out.println(Thread.currentThread().getName()+"->counter="+getCounter()+
":localCounter="+getLocalCounter());
}
public void run() {
for(int i=0;i<100;i++){
addCounter();
addLocalCounter();
display();
}
}
public static void main(String[] args) {
ThreadLocalDemo demo = new ThreadLocalDemo();
}
}
浙公网安备 33010602011771号