1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| import java.util.Random;
public class ThreadLocalDemo {
public static void main(String[] args) throws InterruptedException { final Thread t1 = new Thread(new RandomCounter("线程1")); final Thread t2 = new Thread(new RandomCounter("线程2")); final Thread t3 = new Thread(new RandomCounter("线程3"));
t1.start(); t2.start(); t3.start();
t1.join(); t2.join(); t3.join(); }
private static class RandomCounter implements Runnable { private final ThreadLocal<Integer> integerThreadLocal = new ThreadLocal<>(); private String name;
RandomCounter(String name) { this.name = name; Thread.currentThread().setName(name); }
@Override public void run() { final Random random = new Random(); for (int i = 0; i < 3; i++) {
integerThreadLocal.set(random.nextInt(1000)); System.out.println(name + ": 当前local值为:" + integerThreadLocal.get()); integerThreadLocal.remove(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
|