博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
类InheritableThreadLocal的使用
阅读量:4230 次
发布时间:2019-05-26

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

使用类InheritableThreadLocal可以在子线程中取得父线程继承下来的值。

看栗子:

public class Tools {    public static InheritableThreadLocalExt t1=new InheritableThreadLocalExt();}

public class InheritableThreadLocalExt extends InheritableThreadLocal{    @Override    protected Object initialValue() {        return new Date().getTime();    }}

public class ThreadA extends Thread{    @Override    public void run() {        try{            for(int i=0;i<10;i++){                System.out.println("在ThreadA线程中取值 ="+Tools.t1.get());                Thread.sleep(100);            }        }catch (InterruptedException e){            e.printStackTrace();        }    }}
public class Run {    public static void main(String[] args){        try{            for(int i=0;i<10;i++){                System.out.println(" 在Main线程中取值="+Tools.t1.get());                Thread.sleep(100);            }            Thread.sleep(5000);            ThreadA a=new ThreadA();            a.start();        }catch (InterruptedException e){            e.printStackTrace();        }    }}
可以通过重写childValue方法在继承的同时对值进行进一步的处理

public class InheritableThreadLocalExt extends InheritableThreadLocal{    @Override    protected Object initialValue() {        return new Date().getTime();    }    @Override    protected Object childValue(Object parentValue) {        return parentValue+"我在子线程加的~";    }}

转载地址:http://cmjqi.baihongyu.com/

你可能感兴趣的文章
The Hands-On Project Office: Guaranteeing ROI and On-Time Delivery
查看>>
Expert Oracle9i Database Administration
查看>>
.NET Framework Solutions: In Search of the Lost Win32 API
查看>>
Linux for Embedded and Real-Time Applications
查看>>
Refactoring in Large Software Projects : Performing Complex Restructurings Successfully
查看>>
Semantic Web Technologies : Trends and Research in Ontology-based Systems
查看>>
Linux All-in-One Desk Reference For Dummies
查看>>
Security Patterns : Integrating Security and Systems Engineering
查看>>
Cross-Platform Web Services Using C# & JAVA
查看>>
UML Xtra-Light: How to Specify Your Software Requirements
查看>>
Fundamentals of OOP and Data Structures in Java
查看>>
C++ Network Programming, Vol. 1: Mastering Complexity with ACE and Patterns
查看>>
The Ethical Hack: A Framework for Business Value Penetration Testing
查看>>
Agile Development with ICONIX Process: People, Process, and Pragmatism
查看>>
Practical Guide to Software Quality Management
查看>>
Real Process Improvement Using the CMMI
查看>>
GDI+ Programming in C# and VB .NET
查看>>
Implementing and Integrating Product Data Management and Software Configuration Management
查看>>
Software Configuration Management
查看>>
Agile Project Management: How to Succeed in the Face of Changing Project Requirements
查看>>