1 package com.thread; 2 3 public class ThreadLocalTest { 4 public static void main(String[] args) { 5 final Person p = new Person(); 6 new Thread(new Runnable() { 7 @Override 8 public void run() { 9 p.setName("zhangsan"); 10 p.setAge(100); 11 try { 12 Thread.sleep(1000); 13 } catch (InterruptedException e) { 14 // TODO Auto-generated catch block 15 e.printStackTrace(); 16 } 17 System.out.println("1:"+p.getName()); 18 } 19 }).start(); 20 21 new Thread(new Runnable() { 22 @Override 23 public void run() { 24 p.setName("lisi"); 25 p.setAge(20); 26 try { 27 Thread.sleep(1000); 28 } catch (InterruptedException e) { 29 // TODO Auto-generated catch block 30 e.printStackTrace(); 31 } 32 System.out.println("2:"+p.getName()); 33 } 34 }).start(); 35 } 36 } 37 38 class Person { 39 private String name; 40 private int age; 41 public String getName() { 42 return name; 43 } 44 public void setName(String name) { 45 this.name = name; 46 } 47 public int getAge() { 48 return age; 49 } 50 public void setAge(int age) { 51 this.age = age; 52 } 53 54 }
如上述执行结果:
1:lisi
2:lisi
多个线程共享同一个变量时,如果想让这个变量成为各自线程的一个副本(线程的局部变量),这样每个线程的数据就不会收到其他线程的影响
ThreadLocal很好的解决了这个问题
1 package com.thread; 2 3 public class ThreadLocalTest { 4 public static void main(String[] args) { 5 new Thread(new Runnable() { 6 @Override 7 public void run() { 8 Person.getThreadInstance().setName("zhangsan"); 9 Person.getThreadInstance().setAge(100); 10 try { 11 Thread.sleep(1000); 12 } catch (InterruptedException e) { 13 // TODO Auto-generated catch block 14 e.printStackTrace(); 15 } 16 System.out.println("1:"+Person.getThreadInstance().getName()); 17 } 18 }).start(); 19 20 new Thread(new Runnable() { 21 @Override 22 public void run() { 23 getPerson().setName("lisi"); 24 getPerson().setAge(20); 25 try { 26 Thread.sleep(1000); 27 } catch (InterruptedException e) { 28 // TODO Auto-generated catch block 29 e.printStackTrace(); 30 } 31 System.out.println("2:"+getPerson().getName()); 32 } 33 }).start(); 34 } 35 36 public static Person getPerson(){ 37 return Person.getThreadInstance(); 38 } 39 } 40 41 class Person { 42 private String name; 43 private int age; 44 private static ThreadLocal<Person> local = new ThreadLocal<>(); 45 private static Person p = null; 46 private Person(){ 47 } 48 //这儿可不需要synchonized 49 public static Person getThreadInstance(){ 50 p = local.get(); 51 if(p==null){ 52 p = new Person(); 53 local.set(p); 54 } 55 return p; 56 } 57 public String getName() { 58 return name; 59 } 60 public void setName(String name) { 61 this.name = name; 62 } 63 public int getAge() { 64 return age; 65 } 66 public void setAge(int age) { 67 this.age = age; 68 } 69 70 }