多线程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;
}
}
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;
}
}
相关文章推荐
- 面向对象(封装)与包装类Demo
- C++多线程面向对象封装
- 复习 1 java 面向对象之封装,继承,多态(1)
- Java程序员从笨鸟到菜鸟之(三)面向对象之封装,继承,多态(下)
- Muduo之封装ThreadLocal、ThreadLocalSingleton
- JAVA多线程----ThreadLocal
- React简单解释如何封装组件的demo
- 多线程编程之ThreadLocal的使用和内在原理
- PHP中面向对象封装的数据库(基)类
- 面向对象三大特征——封装
- 黑马程序员——面向对象(封装、构造函数、静态)
- OC基础——面向对象(封装、继承、多态)
- 面向对象的第一个特征:封装II
- 面向对象的第一个特征:封装III
- 黑马程序员--面向对象(一)封装、成员变量与局部变量、匿名对象、构造函数、this关键字
- Java多线程——ThreadLocal
- 黑马程序员_OC语言之面向对象的三大特性(封装、继承、多态)
- c# 多线程入门demo
- 面向对象 封装
- Java程序员从笨鸟到菜鸟之(三)面向对象之封装,继承,多态(下)