java的ThreadLocal类的用法,ThreadLocal是一个支持泛型的类,用在多线程中用于防止并发冲突问题。
例如下面的一个例子,就是用于线程增加1,但是相互不冲突
package com.test.threadlocal;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class Local
{
private static ThreadLocal<Integer> num=new ThreadLocal<Integer>()
{
protected synchronized Integer initialValue()
{
return 1;
}
};
public static void add()
{
num.set(num.get()+1);
}
public static int get()
{
return num.get();
}
}
class SelfThread extends Thread
{
public void run()
{
for(int i=0;i<1000;i++)
{
System.out.println(this.getName()+" "+Local.get());
this.yield();
Local.add();
}
}
}
public class MyThreadLocal {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ExecutorService exec=Executors.newCachedThreadPool();
for(int i=0;i<5;i++)
{
exec.execute(new SelfThread());
}
exec.shutdown();
}
}
输出结果
Thread-3 973
Thread-1 808
Thread-3 974
Thread-1 809
Thread-3 975
Thread-1 810
Thread-3 976
Thread-1 811
Thread-3 977
Thread-1 812
Thread-3 978
Thread-1 813
Thread-3 979
Thread-1 814
Thread-3 980
Thread-1 815
Thread-3 981
Thread-1 816
Thread-3 982
Thread-1 817
Thread-3 983
Thread-1 818
Thread-3 984
Thread-1 819
Thread-3 985
Thread-1 820
Thread-3 986
Thread-1 821
Thread-3 987
Thread-1 822
Thread-3 988
Thread-1 823
Thread-3 989
Thread-1 824
Thread-3 990
Thread-1 825
Thread-3 991
Thread-1 826
Thread-3 992
Thread-1 827
Thread-3 993
Thread-1 828
Thread-3 994
Thread-1 829
Thread-3 995
Thread-1 830
Thread-3 996
Thread-1 831
Thread-3 997
Thread-1 832
Thread-3 998
Thread-1 833
Thread-3 999
Thread-1 834
Thread-3 1000
Thread-1 835
Thread-1 836
Thread-1 837
Thread-1 838
Thread-1 839
Thread-1 840
Thread-1 841
Thread-1 842
Thread-1 843
Thread-1 844
Thread-1 845
Thread-1 846
Thread-1 847
Thread-1 848
Thread-1 849
Thread-1 850
Thread-1 851
Thread-1 852
Thread-1 853
Thread-1 854
Thread-1 855
Thread-1 856
Thread-1 857
Thread-1 858
Thread-1 859
Thread-1 860
Thread-1 861
Thread-1 862
Thread-1 863
Thread-1 864
Thread-1 865
Thread-1 866
Thread-1 867
Thread-1 868
Thread-1 869
Thread-1 870
Thread-1 871
Thread-1 872
Thread-1 873
Thread-1 874
我们发现,线程会相互切换,但是每个线程都保持了增加1的顺序,说明没有线程之间的相互干扰。