SimpleDateFormat这个类,大部分都可能认为是线程安全,或者更本没有想线程不线程的问题。
测试代码:(测试的时候也会有异常抛出,我代码中catch了)
- public class SimpleDateFormatTest extends Thread {
- // 时间
- private static String dateString = "2010-10-01 02:10:9";
- // 加入元素
- private static Set<Long> set = Collections.synchronizedSet(new HashSet<Long>());
- // 控制线程退出
- private static AtomicBoolean ok = new AtomicBoolean(true);
- // 每个线程一个SimpleDateFormat
- // static ThreadLocal<SimpleDateFormat> format = new
- // ThreadLocal<SimpleDateFormat>() {
- // protected SimpleDateFormat initialValue() {
- // SimpleDateFormat format = new SimpleDateFormat();
- // format.applyPattern("yyyy-MM-dd HH:mm:ss");
- // return format;
- // }
- // };
- private static SimpleDateFormat format;
- static {
- format = new SimpleDateFormat();
- format.applyPattern("yyyy-MM-dd HH:mm:ss");
- }
- public void run() {
- while (SimpleDateFormatTest.ok.get()) {
- try {
- set.add(((Date) SimpleDateFormatTest.format
- .parseObject(dateString)).getTime());
- } catch (Exception e) {
- // e.printStackTrace();
- }
- }
- }
- public static void main(String args[]) throws ParseException,
- InterruptedException {
- // 定义线程池
- ExecutorService pools = Executors.newCachedThreadPool();
- // 加入判断逻辑
- pools.execute(new Runnable() {
- public void run() {
- try {
- while (SimpleDateFormatTest.ok.get()) {
- if (SimpleDateFormatTest.set.size() > 2) {
- System.out.println("size"+SimpleDateFormatTest.set.size());
- SimpleDateFormatTest.ok.set(false);
- System.out.println("check error");
- }
- Thread.sleep(1000);
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- });
- // 加入线程 2个
- for (int i = 0; i < 2; i++) {
- pools.execute(new SimpleDateFormatTest());
- }
- // 设置时间
- pools.execute(new Runnable() {
- @Override
- public void run() {
- int i = 0;
- try {
- while (i++ < 10 && SimpleDateFormatTest.ok.get()) {
- System.out.println("check " + i + "s");
- Thread.sleep(1000);
- }
- if (SimpleDateFormatTest.ok.get()) {
- SimpleDateFormatTest.ok.set(false);
- System.out.println("check ok");
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- });
- pools.shutdown();
- }
- }
运行报错:
check 1s
size1598
check error
所以在多线程的环境中,要么用局部变量;要么ThreadLocal,但是这个又不好控制,所以建议 直接局部变量吧!
- static ThreadLocal<SimpleDateFormat> format = new
- ThreadLocal<SimpleDateFormat>() {
- protected SimpleDateFormat initialValue() {
- SimpleDateFormat format = new SimpleDateFormat();
- format.applyPattern("yyyy-MM-dd HH:mm:ss");
- return format;
- }
- };
转:http://blog.youkuaiyun.com/bxyz1203/article/details/6056333