ThreadLocalクラスの使い方

1669 ワード

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() {
				@Override
				public 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();
		}
	}
}