首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

ThreadLocal种用法

2012-08-21 
ThreadLocal类用法package com.companynamepublic class MyData {private static ThreadLocalMyData ma

ThreadLocal类用法

package com.companyname;public class MyData {private static ThreadLocal<MyData> map=new ThreadLocal<MyData>();private MyData() {}public static MyData getInstance(){MyData instance=map.get();  //以当前线程为key,get值if(instance==null)//如果值为空{instance=new MyData();map.set(instance);}return instance;}private String name;private int age;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}

?

package com.companyname;import java.util.Random;public class ThreadLocalTest {private static Object lock=new Object();public static void main(String[] args) {for (int i = 0; i < 3; i++) {new Thread(new Thread() {@Overridepublic void run() {synchronized (lock) {int temp=new Random().nextInt();MyData d1 = MyData.getInstance();d1.setName("ID"+temp);d1.setAge(temp);System.out.print(Thread.currentThread().getName()+"::");System.out.println(d1.getName()+"::"+d1.getAge());MyData d2 = MyData.getInstance();System.out.println(d2.getName()+"d2::"+d2.getAge());}}}).start();}}}

?

热点排行