java threadLocal 测试

package thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadLocalTest {

	public ThreadLocalTest()

	{

	}

	public static void main(String[] args) throws Exception {
		new ThreadLocalTest().test3();
	}

	private static final ThreadLocal<Content> tl = new ThreadLocal<Content>();

	private ExecutorService executorService = Executors.newFixedThreadPool(2);

	public void set() {
		Content content = new Content();
		System.out.println("set hashCode=" + content.hashCode());
		tl.set(content);
	}

	void test3() throws Exception

	{

		System.out.println("begin");
		executorService.execute(new Runnable() {
			@Override
			public void run() {
				set();
				
			}
		});
		// 线程销不会回收,线程没结束
		Thread.sleep(2000);
		System.out.println("request gc");
		System.gc();
		Thread.sleep(1000);
		
		executorService.shutdown();
		// 线程销会回收
		Thread.sleep(2000);
		System.out.println("request gc");
		System.gc();
		Thread.sleep(1000);
		

		System.out.println("end");

	}

	void test2() throws Exception

	{

		System.out.println("begin");
		new Thread() {
			public void run() {
				set();
				// 线程销毁会回收,線程執行借宿
			}
		}.start();

		Thread.sleep(2000);
		System.out.println("request gc");
		System.gc();
		Thread.sleep(1000);

		System.out.println("end");

	}

	void test1() throws Exception

	{

		System.out.println("begin");

		set();
		System.out.println("try to release content data");

		tl.set(null);// @1
		// tl.remove();//@2

		// 会回收
		System.out.println("request gc");
		System.gc();
		Thread.sleep(1000);

		System.out.println("end");

	}

}

class Content

{

	// /byte data[] = new byte[1024 * 1024 * 10];

	protected void finalize()

	{
		System.out.println("I am released" + hashCode());

	}

	@Override
	public int hashCode() {
		// TODO Auto-generated method stub
		return super.hashCode();
	}

}

猜你喜欢

转载自m635674608.iteye.com/blog/2268929