ThreadLocal线程不安全

80 阅读1分钟

注意第二个箭头的static,因为new一个thread时新的引用 应用的对象始终时static的number,所以5个线程修改的是同一个对象,所以就不安全了。

解决方案就是把static去掉,那么修改的就是5个不同的对象。

或者new ThreadLocal()   的时候给值做初始化。

public class ThreadLocalUnsafe implements Runnable {

 public static ThreadLocal value = new ThreadLocal() {    };    

public static Number number = new Number(0);

    public void run() {

        //每个线程计数加一

        number.setNum(number.getNum()+1);

      //将其存储到ThreadLocal中

        value.set(number);

        SleepTools.ms(2);

        //输出num值

        System.out.println(Thread.currentThread().getName()+"="+value.get().getNum());

    }

    public static ThreadLocal value = new ThreadLocal() {

    };

    public static void main(String[] args) {

        for (int i = 0; i < 5; i++) {

            new Thread(new ThreadLocalUnsafe()).start();

        }

    }

    private static class Number {

        public Number(int num) {

            this.num = num;

        }

        private int num;

        public int getNum() {

            return num;

        }

        public void setNum(int num) {

            this.num = num;

        }

        @Override

        public String toString() {

            return "Number [num=" + num + "]";

        }

    }

}