您的位置:首页 > 其它

多线程demo-ThreadLocal面向对象的封装

2015-02-06 10:48 369 查看
package Thread;

import java.util.Random;

import java.util.concurrent.TimeUnit;

/**

* ThreadLocal示例

*/

public class ThreadLocalTest {

public static void main(String[] args) {

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

new Thread(){

public void run() {

Person.getInstance().setAge(new Random().nextInt(100));

try {

TimeUnit.SECONDS.sleep(new Random().nextInt(4));

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

System.out.println(Thread.currentThread().getName() +"---get---"+
Person.getInstance().getAge());

};

}.start();

}

Person.clear();

}

}

class Person{

private static ThreadLocal<Person> threadLocal = new ThreadLocal<Person>();

private int age;

//关键代码

public static Person getInstance(){

Person person = threadLocal.get();//每个线程对应一个实例

if(person ==null){

person = new Person();

threadLocal.set(person);

}

return person;

}

public static void clear(){

threadLocal.remove();

}

public int getAge() {

return age;

}

public void setAge(int age) {

System.out.println(Thread.currentThread().getName() +"----set----"+ age);

this.age = age;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: