ThreadLocal的作用
发布日期:2021-09-16 12:20:03 浏览次数:5 分类:技术文章

本文共 2538 字,大约阅读时间需要 8 分钟。

例子一:
public class Test6 extends Thread{public static void main(String[] args) {	new Test6().start();	new Test6().start();}public void run(){	test();}static ThreadLocal
local=new ThreadLocal
();//ThreadLocal是用资源空间换取时间的做法//ThreadLocal底层代码使用一个静态的内部类ThreadLocalMap存储副本变量,好让另一个线程使用static int num;public void test(){ while(true){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"::"+local.get()+"::"+num++); if(local.get()==null){ local.set(0); }else{ int temp=local.get(); local.set(++temp); } }}}/* 输出结果如下: Thread-0::null::0 Thread-1::null::1 Thread-0::0::2 Thread-1::0::3 Thread-0::1::4 Thread-1::1::5 Thread-0::2::6 Thread-1::2::7 Thread-0::3::8 Thread-1::3::9*/

例子二:

public class Test8 {static Map
map=new HashMap
();//static int data;public static void main(String[] args) { for(int i=0;i<2;i++){ new Thread(){ public void run(){ int num=new Random().nextInt(); System.out.println("has put : "+num);// data=num; map.put(Thread.currentThread(), num); new A().getData(); new B().getData(); } }.start(); }}static class A{ public void getData(){ System.out.println(Thread.currentThread().getName()+": A data:"+/*data*/map.get(Thread.currentThread())); }}static class B{ public void getData(){ System.out.println(Thread.currentThread().getName()+": B data:"+/*data*/map.get(Thread.currentThread())); }}}
例子三:
public class Test9 {public static void main(String[] args) {	for(int i=0;i<2;i++){		new Thread(new Runnable(){			public void run(){				int num=new Random().nextInt();				MyThreadScopeData ins=MyThreadScopeData.getThreadInstance();				System.out.println(Thread.currentThread().getName()+":num:"+num);				ins.setData(num);				ins.setName("name:"+num);				ins.getData();				ins.getName();			}		}).start();	}}}class MyThreadScopeData{	private static ThreadLocal
local=new ThreadLocal
(); private MyThreadScopeData(){}//单例模式 public static MyThreadScopeData getThreadInstance(){ MyThreadScopeData mythread=local.get(); if(mythread==null){ local.set(new MyThreadScopeData()); } return local.get(); } private String name; private Integer data; public void getName() { System.out.println(Thread.currentThread().getName()+":"+name); } public void setName(String name) { this.name = name; } public void getData() { System.out.println(Thread.currentThread().getName()+":"+data); } public void setData(Integer data) { this.data = data; }}

转载地址:https://blog.csdn.net/wxwzy738/article/details/7484909 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:对map中的value进行排序
下一篇:多线程的创建方式

发表评论

最新留言

路过,博主的博客真漂亮。。
[***.116.15.85]2024年04月22日 15时55分33秒