簡単なthreadlocalシミュレーションとテスト

3279 ワード

詳細
package org.vic.demo.ThreadLocal.threadLocal;

import java.util.HashMap;
import java.util.Map;

public class MyThreadLocal {

	private static Map threadLocalPool = new HashMap<>();
	
	/**
	 * get duplicate object.
	 */
	public T get() {
		Thread currentThread = Thread.currentThread();
		@SuppressWarnings("unchecked")
		T t = threadLocalPool.get(currentThread) == null ? null : (T) threadLocalPool.get(currentThread);
		return t;
	}

	/**
	 * set object to duplicate
	 */
	public void set(T t) {
		Thread currentThread = Thread.currentThread();
		threadLocalPool.put(currentThread, t);
	}
	

        /**
        * remove thread and duplication from the pool
        */
	public void remove() {
		Thread thread = Thread.currentThread();
		threadLocalPool.remove(thread);
		System.out.println("thread " + thread.getName() + " has been removed!");
	} 
	
}

 
 
 
 
package org.vic.demo.ThreadLocal.test;

import java.util.Random;

import org.vic.demo.ThreadLocal.threadLocal.MyThreadLocal;

public class Test implements Runnable {
	
	private static MyThreadLocal threadLocal = new MyThreadLocal();
	
	public void doTest () {
		String currentThreadName = Thread.currentThread().getName();
		System.out.println("current thread name is " + currentThreadName);
		Random ran = new Random();
		int age = ran.nextInt(20);
		System.out.println(currentThreadName + " got age : " + age);
		Student stu = this.getStudenByThreadLocal();
		stu.setName(currentThreadName);
		stu.setAge(age);
		System.out.println("thread name (student name) is " + stu.getName() + " and age is " + stu.getAge());
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("thread name (student name) is " + stu.getName() + " and age is " + stu.getAge());
		threadLocal.remove();
	}
	
	public Student getStudenByThreadLocal () {
		Student stu = (Student) threadLocal.get();
		if (stu == null) {
			stu = new Student();
			threadLocal.set(stu);
		}
		return stu;
	}

	@Override
	public void run() {
		doTest();
	}
	
	public static void main(String[] args) {
		Test t = new Test();
		Thread thr1 = new Thread(t, "thr1");
		Thread thr2 = new Thread(t, "thr2");
		thr1.start();
		thr2.start();
	}
	
}

class Student {
	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;
	}
	
}