java threadLocal 测试

来源:互联网 发布:新手音乐制作软件 编辑:程序博客网 时间:2024/05/29 19:29
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() {@Overridepublic 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());}@Overridepublic int hashCode() {// TODO Auto-generated method stubreturn super.hashCode();}}

 

0 0
原创粉丝点击