• 多线程15--线程本地变量ThreadLocal


    1.

     1 public class ConnThreadLocal {
     2 
     3     //线程变量副本,每个线程都有一个,所以多线程的时候,就不会出现覆盖.而是每个线程一个
     4     public static ThreadLocal<String> th = new ThreadLocal<String>();
     5     
     6     public void setTh(String value){
     7         th.set(value);
     8     }
     9     public void getTh(){
    10         System.out.println(Thread.currentThread().getName() + ":" + this.th.get());
    11     }
    12     
    13     public static void main(String[] args) throws InterruptedException {
    14         
    15         final ConnThreadLocal ct = new ConnThreadLocal();
    16         Thread t1 = new Thread(new Runnable() {
    17             @Override
    18             public void run() {
    19                 ct.setTh("张三");
    20                 ct.getTh(); //t1:张三
    21             }
    22         }, "t1");
    23         
    24         Thread t2 = new Thread(new Runnable() {
    25             @Override
    26             public void run() {
    27                 try {
    28                     Thread.sleep(1000);
    29                     ct.setTh("李四");
    30                     ct.getTh();//t2:李四
    31                 } catch (InterruptedException e) {
    32                     e.printStackTrace();
    33                 }
    34             }
    35         }, "t2");
    36         
    37         t1.start();
    38         t2.start();
    39     }
    40     
    41 }
    View Code
  • 相关阅读:
    hello word
    HDU 1006 Tick and Tick
    HDU 1005 Number Sequence
    HDU 1004 Let the Balloon Rise
    HDU 1003 Max Sum
    HDU 1002 A + B Problem II
    HDU 1001 Sum Problem
    HDU 1000 A + B Problem
    POJ 2253 Frogger
    POJ 2387 Til the Cows Come Home
  • 原文地址:https://www.cnblogs.com/bravolove/p/7953488.html
Copyright © 2020-2023  润新知