引出多线程操作共享变量
package com.hfview.thread;
/**
* 引出多线程共享变量的问题
* @author zhw
*
*/
public class ThreadDemo3 {
/**
* @param args
*/
private static int num;
public static void main(String[] args) {
new Thread( new Runnable() {
public void run() {
num=5;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" "+num);
}
}).start();
new Thread( new Runnable() {
public void run() {
num=10;
System.out.println(Thread.currentThread().getName()+" "+num);
}
}).start();
}
}
结果:
这样就不是线程范围内共享的
编写自定义Map存线程内变量
package com.hfview.thread;
import java.util.HashMap;
import java.util.Map;
/**
* 引出多线程共享变量的问题
* @author zhw
*
*/
public class ThreadDemo3 {
/**
* @param args
*/
private static int num;
private static Map<Thread,Integer> map= new HashMap<Thread,Integer>();
public static void main(String[] args) {
new Thread( new Runnable() {
public void run() {
num=5;
map.put(Thread.currentThread(), num);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" "+map.get(Thread.currentThread()));
}
}).start();
new Thread( new Runnable() {
public void run() {
num=10;
map.put(Thread.currentThread(), num);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" "+map.get(Thread.currentThread()));
}
}).start();
}
}
这样线程范围内的变量总是属于自己的
ThreadLocal的应用
package com.hfview.thread;
import java.util.HashMap;
import java.util.Map;
/**
* 引出多线程共享变量的问题
* @author zhw
*
*/
public class ThreadDemo3 {
/**
* @param args
*/
private static int num;
private static Map<Thread,Integer> map= new HashMap<Thread,Integer>();
private static ThreadLocal<Integer> tl =new ThreadLocal<Integer>();
public static void main(String[] args) {
new Thread( new Runnable() {
public void run() {
num=5;
//map.put(Thread.currentThread(), num);
tl.set(num);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
//System.out.println(Thread.currentThread().getName()+" "+map.get(Thread.currentThread()));
System.out.println(Thread.currentThread().getName()+" "+tl.get());
}
}).start();
new Thread( new Runnable() {
public void run() {
num=10;
//map.put(Thread.currentThread(), num);
tl.set(num);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
//System.out.println(Thread.currentThread().getName()+" "+map.get(Thread.currentThread()));
System.out.println(Thread.currentThread().getName()+" "+tl.get());
}
}).start();
}
}
这里达到的效果和上面通过Map的一样,这也是TreadLocal的原理,如果有两个共享变量就定义两个TreadLocal,如果有很多变量就顶一个实体存储这些变量,然后定义一个TreadLocal存储这个实体