1、简介
2、API
全局变量并发导致数据不一致问题:
package com.xxx.util;
import java.util.Date;
import java.util.concurrent.TimeUnit;
/**
* Created with IntelliJ IDEA.
* Date: 15-4-1
* Time: 上午11:37
* To change this template use File | Settings | File Templates.
*/
public class ThreadUnsafeVar implements Runnable{
private Date date;
@Override
public void run() {
date = new Date();
System.out.printf("Starting Thread:%s:%s\n",Thread.currentThread().getId(),date);
try {
//返回其值最接近参数并且是整数的 double 值
int sleepSeconds = (int)Math.rint(Math.random()*10);
System.out.printf("Starting Thread:%s:%s\n",Thread.currentThread().getId(),sleepSeconds);
TimeUnit.SECONDS.sleep(sleepSeconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("Ending Thread:%s:%s\n",Thread.currentThread().getId(),date);
}
}
线程局部变量为每一个线程保存一份数据:
package com.xxx.util;
import java.util.Date;
import java.util.concurrent.TimeUnit;
/**
* Created with IntelliJ IDEA.
* Date: 15-4-1
* Time: 上午11:37
* To change this template use File | Settings | File Templates.
*/
public class ThreadLocalVar implements Runnable{
private static ThreadLocal localDate = new ThreadLocal(){
protected Date initialValue(){
return new Date();
}
};
@Override
public void run() {
System.out.printf("Starting Thread:%s:%s\n",Thread.currentThread().getId(),localDate.get());
try {
//返回其值最接近参数并且是整数的 double 值
int sleepSeconds = (int)Math.rint(Math.random()*10);
System.out.printf("Starting Thread:%s:%s\n",Thread.currentThread().getId(),sleepSeconds);
TimeUnit.SECONDS.sleep(sleepSeconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("Ending Thread:%s:%s\n",Thread.currentThread().getId(),localDate.get());
}
}
main类:
package com.xxx.util;
import java.util.concurrent.TimeUnit;
/**
* Created with IntelliJ IDEA.
* Date: 15-4-1
* Time: 上午11:42
* To change this template use File | Settings | File Templates.
*/
public class ThreadVarMain {
public static void main(String[] args){
//ThreadUnsafeVar threadVar = new ThreadUnsafeVar();
ThreadLocalVar threadVar = new ThreadLocalVar();
for(int i=0;i<10;i++){
Thread thread = new Thread(threadVar);
thread.start();
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
4、运行结果
全局变量运行结果:
局部变量运行结果:
当使用全局变量时,每个线程变量的值都会随线程的并发而改变。使用线程局部变量,每个线程都维护各自的变量,互不影响。
http://lavasoft.blog.51cto.com/62575/51926/