ThreadLocal - Java多线程编程
生活随笔
收集整理的這篇文章主要介紹了
ThreadLocal - Java多线程编程
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
多線程是JAVA實現多任務的基礎:1. 通過Thread來啟動一個新的線程2. ExecutorService3. ScheduleThreadPool4. Fork/Join 多線程框架來完成多任務Thread對象還代表一個線程1. 當我們調用Thread.currentThread()的時候我們就獲取到了當前的線程
通常我們要對每一個任務啟動一個新的線程例如對于每個訪問WEB程序的任務,我們都會啟動一個新的線程,來處理這個用戶的請求,當然我們也可以啟動線程池,取出一個空閑的線程來處理,那么我們如何在一個線程內傳遞一個狀態呢例如我們在一個線程的處理過程中,還經常需要調用不同的類來處理不同的功能,我們如何在當前的線程中獲取當前的用戶
當我們定義一個ThreadLocal對象的時候,我們可以通過set方法對當前對象綁定一個值然后我們可以通過get()方法隨時得到一個已經綁定的一個值,接下來我們通過remove()方法
通過set方法綁定一個user對象以后,我們調用step1然后通過get()方法獲取當前的user,緊接著我們調用printUser(),然后通過get()方法返回當前的user方法調用一定是同一個方法執行的,get()方法獲取的是同一個user對象
ThreadLocal一定要在finally里面清除如果沒有被清除,這個線程在執行其它代碼的時候,就會把上一次的狀態帶進去.
package com.leon.day05;class User {String name;int level;public User(String name, int level) {this.name = name;this.level = level;}
}/*** 緊接著我們定義一個UserContext類,繼承自AutoCloseable* @author Leon.Sun**/
class UserContext implements AutoCloseable {/*** 全局唯一靜態變量,表示當前線程關聯的User對象*/static final ThreadLocal<User> context = new ThreadLocal<>();/*** 獲取當前線程的ThreadLocal USer* 返回的當前對象* @return*/public static User getCurrentUser() {return context.get();}/*** 初始化ThreadLocal的User* 當我們創建user對象的時候我們就把它放入local中* @param user*/public UserContext(User user) {context.set(user);}/*** 移除ThreadLocal關聯的User* 當我們調用close方法的時候,我們就移除了關聯的user*/public void close() {context.remove();}
}
class ProcessThread extends Thread {User user;public ProcessThread(User user) {this.user = user;}public void run() {try (UserContext ctx = new UserContext(user)) {// step1:new Greeting().hello();// step2:Level.checkLevel();// step3:// TODO:}}
}
class Greeting {void hello() {// 返回當前線程關聯的userUser user = UserContext.getCurrentUser();System.out.println("Hello, " + user.name + "!");}
}
class Level {static void checkLevel() {User user = UserContext.getCurrentUser();if (user.level > 100) {System.out.println(user.name + " is a VIP user.");}else{System.out.println(user.name + " is a registered user.");}}
}
public class Main {// 最后我們在main方法中啟動兩個Thread,分別關聯兩個不同的user對象public static void main(String[] args) throws Exception{Thread t1 = new ProcessThread(new User("Bob", 120));Thread t2 = new ProcessThread(new User("Alice", 98));t1.start();t2.start();t1.join();t2.join();System.out.println("Main end");}
}
我們可以把ThreadLocal看成是全局的Map<Thread,Object>每一個線程獲取ThreadLocal變量的時候,使用Thread自身作為KeyThreadLocal表示線程的局部變量,它確保每個線程的ThreadLocal變量都是各自獨立的.ThreadLocal適合在一個線程的處理流程中保持上下文(避免了同一個參數在所有方法中傳遞)使用ThreadLocal要用try...finally結構
?
總結
以上是生活随笔為你收集整理的ThreadLocal - Java多线程编程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Fork_Join - Java多线程编
- 下一篇: 浅析若干Java序列化工具