/**
*
* <b>Application name:ThreadLocal</b><br>
* <b>Application describing:</b> <br>
* 由于线程访问公共变量时需要加锁,加锁会令线程等待,降低并发程序的运行效率。ThreadLocal用于存储线程级变量,在可以的情况下,
* 可以把资源复制多份,每个线程一份,这就可以不用加线程锁了。另外,如果在线程上游方法设置线程变量,线程下流方法都可以读取该变量,可以模拟实现参数传递。
*/
public class TheadLocalDemo
{
private static ThreadLocal<MyConnnection> local=new ThreadLocal<MyConnnection>();
/**
*
* {方法功能中文描述}
*
*/
public void method1()
{
System.out.println("方法1运行,设置线程变量。");
TheadLocalDemo.local.set(new MyConnnection("jdbc:oracle:thin:@192.168.137.23:1521:orcl","oracle"));
}
/**
*
* {方法功能中文描述}
*
*/
public void method2()
{
System.out.println("方法2运行。");
}
/**
*
* {方法功能中文描述}
*
*/
public void method3()
{
System.out.println("方法3运行,获取线程变量。");
MyConnnection con=TheadLocalDemo.local.get();
System.out.println(con.getUrl()+"|"+con.getType());
}
/**
*
* {方法功能中文描述}
*
* @param args
*/
public static void main(String[] args)
{
TheadLocalDemo demo=new TheadLocalDemo();
demo.method1();
demo.method2();
demo.method3();
}
}
/**
*
* <b>Application name:</b><br>
* <b>Application describing:线中存储的的类型</b> <br>
*/
class MyConnnection{
private String url;
private String type;
/**
* {方法功能中文描述}
*
* @param url
* @param type
*/
public MyConnnection(String url, String type)
{
this.url = url;
this.type = type;
}
/**
* type的GET方法
* @return String type.
*/
public String getType()
{
return type;
}
/**
* type的SET方法
* @param type The type to set.
*/
public void setType(String type)
{
this.type = type;
}
/**
* url的GET方法
* @return String url.
*/
public String getUrl()
{
return url;
}
/**
* url的SET方法
* @param url The url to set.
*/
public void setUrl(String url)
{
this.url = url;
}
}
ThreadLocal简析
最新推荐文章于 2021-08-02 21:24:02 发布
本文通过示例介绍了ThreadLocal的概念及其在解决线程间资源共享问题时的优势,展示了如何在Java中使用ThreadLocal来存储线程级变量,避免了线程锁的使用,提升了并发程序的运行效率。
8740

被折叠的 条评论
为什么被折叠?



