public class ThreadUtil {
public static void main(String[] args) throws InterruptedException {
PrimeRun p = new PrimeRun();
System.out.println("多线程中的变量:");
for(int i=0;i<10;i++){
new Thread(p).start();
}
Thread.sleep(1000);
System.out.println("当前线程中的变量:");
System.out.println(p.getParam()+">>>>>>"+p.getT().get());
}
}
public class PrimeRun implements Runnable {
private static int param=0;
private static ThreadLocal t=new ThreadLocal();
static{
t.set(0);
}
public void run() {
t.set(param++);
System.out.println(param+">>"+t.get());
}
public static int getParam() {
return param;
}
public static void setParam(int param) {
PrimeRun.param = param;
}
public static ThreadLocal getT() {
return t;
}
public static void setT(ThreadLocal t) {
PrimeRun.t = t;
}
}运行结果::
多线程中的变量:
1>>0
2>>1
3>>2
5>>4
5>>3
7>>5
8>>7
9>>8
7>>6
10>>9
当前线程中的变量:
10>>>>>>0
说明:::
1. ThreadLocal变量在各个线程中相互独立,即:操作的只是[b]ThreadLocal变量的副本[/b],本身并没有改变。
2. Runnable,Thread 只是实现多线程的一种方式,非ThreadLocal变量在各个线程中是共享的,即:操作的是[b]变量本身[/b]。
10万+

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



