Java獲取線程ID的實例
以下實例演示了如何使用 getThreadId() 方法獲取線程id:
public class Main extends Object implements Runnable { private ThreadID var; public Main(ThreadID v) { this.var = v; } public void run() { try { print('var getThreadID =' + var.getThreadID()); Thread.sleep(2000); print('var getThreadID =' + var.getThreadID()); } catch (InterruptedException x) { } } private static void print(String msg) { String name = Thread.currentThread().getName(); System.out.println(name + ': ' + msg); } public static void main(String[] args) { ThreadID tid = new ThreadID(); Main shared = new Main(tid); try { Thread threadA = new Thread(shared, 'threadA'); threadA.start(); Thread.sleep(500); Thread threadB = new Thread(shared, 'threadB'); threadB.start(); Thread.sleep(500); Thread threadC = new Thread(shared, 'threadC'); threadC.start(); } catch (InterruptedException x) { } }} class ThreadID extends ThreadLocal { private int nextID; public ThreadID() { nextID = 10001; } private synchronized Integer getNewID() { Integer id = new Integer(nextID); nextID++; return id; } protected Object initialValue() { print('in initialValue()'); return getNewID(); } public int getThreadID() { Integer id = (Integer) get(); return id.intValue(); } private static void print(String msg) { String name = Thread.currentThread().getName(); System.out.println(name + ': ' + msg); }}
以上代碼運行輸出結(jié)果為:
threadA: in initialValue()threadA: var getThreadID =10001threadB: in initialValue()threadB: var getThreadID =10002threadC: in initialValue()threadC: var getThreadID =10003threadA: var getThreadID =10001threadB: var getThreadID =10002threadC: var getThreadID =10003
以上就是Java獲取線程ID的實例的詳細(xì)內(nèi)容,更多關(guān)于Java獲取線程ID的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 解決vue頁面刷新,數(shù)據(jù)丟失的問題2. python 讀txt文件,按‘,’分割每行數(shù)據(jù)操作3. python logging.info在終端沒輸出的解決4. vue路由分文件拆分管理詳解5. vue+vuex+axios從后臺獲取數(shù)據(jù)存入vuex,組件之間共享數(shù)據(jù)操作6. 詳解android adb常見用法7. SpringBoot使用Captcha生成驗證碼8. android studio實現(xiàn)簡單的計算器(無bug)9. android 控件同時監(jiān)聽單擊和雙擊實例10. Python 忽略文件名編碼的方法
