---
title: "试试ThreadLocal"
author: "includemain"
date: "2010-05-25T10:27:12Z"
tags: []
categories: ["编程语言"]
slug: "threadlocal"
draft: false
lastmod: "2010-05-31T01:03:53Z"
id: 674707
url: "https://indiff.iteye.com/blog/674707"
---

```java

public final class Resource {
	private static Resource instance = new Resource();

	private Resource() {
		System.err.println("The resource initializing...!");
	}

	public static Resource getInstance() {
		return instance;
	}

	public void start() {
		System.err.println("The resource starting...!");
	}

	public void end() {
		System.err.println("The resource ending...!");
	}

	public void destory() {
		System.err.println("The resource destroying...!");
	}
}

```



```java

/**
 * Use the thread locale 
 * @author Administrator
 */
public final class ResourceUtil {
	private static ThreadLocal<Resource> resHandler = new ThreadLocal<Resource>();
	
	public final static Resource getResource() {
		Resource resource = resHandler.get();
		if (resource == null) {
			resource = Resource.getInstance();
			resHandler.set(resource);
		}
		return resource;
	}
	
	public final static void work() {
		Resource resource = getResource();
		resource.start();
		resource.end();
		destroy();
	}
	
	public final static void destroy() {
		Resource resource = resHandler.get();
		if (resource != null) {
			resource.destory();
			resHandler.remove();
		}
		resource = null;
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new Thread() {
			@Override
			public void run() {
				ResourceUtil.work();
				System.err.println(Thread.currentThread() + " : go away!");
			}
		}.start();
		new Thread() {
			@Override
			public void run() {
				ResourceUtil.work();
				System.err.println(Thread.currentThread() + " : go away!");
			}
		}.start();
		new Thread() {
			@Override
			public void run() {
				ResourceUtil.work();
				System.err.println(Thread.currentThread() + " : go away!");
			}
		}.start();
		new Thread() {
			@Override
			public void run() {
				ResourceUtil.work();
				System.err.println(Thread.currentThread() + " : go away!");
			}
		}.start();
		new Thread() {
			@Override
			public void run() {
				ResourceUtil.work();
				System.err.println(Thread.currentThread() + " : go away!");
			}
		}.start();
		new Thread() {
			@Override
			public void run() {
				ResourceUtil.work();
				System.err.println(Thread.currentThread() + " : go away!");
			}
		}.start();
		new Thread() {
			@Override
			public void run() {
				ResourceUtil.work();
				System.err.println(Thread.currentThread() + " : go away!");
			}
		}.start();
		new Thread() {
			@Override
			public void run() {
				ResourceUtil.work();
				System.err.println(Thread.currentThread() + " : go away!");
			}
		}.start();
		
	}

}

```