什么叫线程安全&从哪里考虑
什么叫线程安全&从哪里考虑
线程封闭
线程封闭可以保证线程安全,ThreadLocal这个类可以实现线程封闭
实例1
线程不封闭
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| public class Demo01ThreadLocal { volatile static Person p = new Person();
public static void main(String[] args) { new Thread(()->{ try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(p.name); }).start();
new Thread(()->{ try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } p.name = "李四"; }).start(); } }
class Person{ String name = "张三"; }
|

一个线程对共享数据的修改影响到了另一个线程
线程封闭
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| public class Demo02ThreadLocal { static ThreadLocal<Person> tl = new ThreadLocal<>();
public static void main(String[] args) { new Thread(()->{ try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(tl.get()); }).start();
new Thread(()->{ try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } tl.set(new Person()); }).start(); } }
|

ThreadLocal实现了每个线程往里面放的东西,只有这个线程自己能取出来用,不会有其它的线程的干扰,就像超市门口的临时储物柜(从表面上看),这就是它所实现的功能。