Java線程與並發庫進階應用程式-線程範圍內共用資料ThreadLocal類

來源:互聯網
上載者:User

標籤:adl   get   runnable   log   自身   回調   nis   random   remove   

1.線程範圍內共用變數

  

1.1 前奏:

使用一個Map來實現線程範圍內共用變數

  

public class ThreadScopeShareData {    static Map<Thread, Integer> dataMap = new HashMap<Thread, Integer>();    public static void main(String[] args) {        for (int i = 0; i < 2; i++) {            new Thread(new Runnable() {                @Override                public void run() {                    int data = new Random().nextInt(); // 擷取一個隨機整數                    System.out.println(Thread.currentThread().getName()                            + " put data " + data);                    dataMap.put(Thread.currentThread(), data);                    new A().get();                    new B().get();                }            }).start();        }    }    static class A {        public void get() {            System.out.println(Thread.currentThread().getName() + " get data "                    + dataMap.get(Thread.currentThread()));        }    }    static class B {        public void get() {            System.out.println(Thread.currentThread().getName() + "get data "                    + dataMap.get(Thread.currentThread()));        }    }}

 

  

1.2 ThreadLocal類實際上就是一種map

/** * ThreadLocal 類 這裡ThreadLocal存放一個變數,如果有多個變數, 可以先將多個變數封裝為一個對象 *  * @author Administrator *  */public class ThreadLocalTest {    static ThreadLocal<Integer> x = new ThreadLocal<>(); //    public static void main(String[] args) { //        for (int i = 0; i < 2; i++) {            new Thread(new Runnable() {                @Override                public void run() {                    int data = new Random().nextInt(); // 擷取一個隨機整數                    System.out.println(Thread.currentThread().getName()                            + " put data " + data);                    x.set(data);                    new A().get();                    new B().get();                }            }).start();        }    }    static class A {        public void get() {            System.out.println(Thread.currentThread().getName() + " get data "                    + x.get());        }    }    static class B {        public void get() {            System.out.println(Thread.currentThread().getName() + "get data "                    + x.get());        }    }}

 2.線程範圍內共用多個變數,可以將多個變數封裝為一個對象

/** * ThreadLocal 類 這裡ThreadLocal存放一個變數,如果有多個變數, 可以先將多個變數封裝為一個對象 *  * @author Administrator *  */public class ThreadLocalTest {    static ThreadLocal<Integer> x = new ThreadLocal<>(); //    public static void main(String[] args) { //        for (int i = 0; i < 2; i++) {            new Thread(new Runnable() {                @Override                public void run() {                    int data = new Random().nextInt(); // 擷取一個隨機整數                    System.out.println(Thread.currentThread().getName()                            + " put data " + data);                    x.set(data);                    MyThreadScopeData myData = MyThreadScopeData.getThreadInstance();//擷取與線程綁定的對象                    myData.setName("name"+data);                    myData.setAge(data);                    System.out.println(Thread.currentThread().getName()                            + " put Object " + "name: "+myData.getName()+","+" age: "+myData.getAge());                    new A().get();                    new B().get();                }            }).start();        }    }    static class A {        public void get() {            System.out.println(Thread.currentThread().getName() + " get data "                    + x.get());            MyThreadScopeData instance = MyThreadScopeData.getThreadInstance(); //直接擷取與該線程相關的對象            System.out.println(Thread.currentThread().getName() + " get Object "                    + "name: "+instance.getName()+","+" age: "+instance.getAge());        }    }    static class B {        public void get() {            System.out.println(Thread.currentThread().getName() + "get data "                    + x.get());            MyThreadScopeData instance = MyThreadScopeData.getThreadInstance(); //直接擷取與該線程相關的對象            System.out.println(Thread.currentThread().getName() + " get Object "                    + "name: "+instance.getName()+","+" age: "+instance.getAge());        }    }}// 單例class MyThreadScopeData {  //類的執行個體是與線程相關的,那麼類的設計就交由類自身完成,只要調用自然就是與線程有關的     private static ThreadLocal<MyThreadScopeData> map = new ThreadLocal<>();    private MyThreadScopeData() {    }    public static MyThreadScopeData getThreadInstance() { // 線程間是相互獨立的,這裡不需要考慮同步        MyThreadScopeData instance = map.get();        if (instance == null) {            instance = new MyThreadScopeData();            map.set(instance);        }        return instance;    }    private String name;    private Integer age;    /**     * @return the name     */    public String getName() {        return name;    }    /**     * @param name     *            the name to set     */    public void setName(String name) {        this.name = name;    }    /**     * @return the age     */    public Integer getAge() {        return age;    }    /**     * @param age     *            the age to set     */    public void setAge(Integer age) {        this.age = age;    }}

 

列印結果

Thread-1 put data -723086824
Thread-0 put data 772514756
Thread-1 put Object name: name-723086824, age: -723086824
Thread-0 put Object name: name772514756, age: 772514756
Thread-0 get data 772514756
Thread-1 get data -723086824
Thread-0 get Object name: name772514756, age: 772514756
Thread-1 get Object name: name-723086824, age: -723086824
Thread-0get data 772514756
Thread-1get data -723086824
Thread-0 get Object name: name772514756, age: 772514756
Thread-1 get Object name: name-723086824, age: -723086824

類的執行個體是與線程相關的,那麼類的設計就交由類自身完成,只要調用自然就是與線程有關的  strust2的主要思想就是這麼設計的

參看JAVA API

ThreadLocal有一個 remove()方法

可以移除與該線程相關的變數

remove()
Removes the current thread‘s value for this thread-local variable.

 

補充:

  虛擬機器的對應類 Runtime ,中有一個方法 addShutdownHook(Thread hook)

  addShutdownHook(Thread hook)
  Registers a new virtual-machine shutdown hook.

  例如可以寫一個發送郵件的線程Thread,當虛擬機器掛掉之前會調用傳入的Thread,發送一封郵件。

線程中是不是也應該有這種機制,當一個線程掛掉之前可以執行一個之前註冊好的事件,或者有一個監聽器在監聽線程的狀態,從而進行回調

在擷取到線程掛掉的通知,就可以把該線程相關的變數全部remove擷取clear掉

  

 

Java線程與並發庫進階應用程式-線程範圍內共用資料ThreadLocal類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.