java基础---->多线程之ThreadLocal(七)

时间:2022-07-19 04:20:18

  这里学习一下java多线程中的关于ThreadLocal的用法。人时已尽,人世还长,我在中间,应该休息。

ThreadLocal的简单实例

一、ThreadLocal的简单使用

package com.linux.huhx.thread2;

import java.util.Random;

public class ThreadLocalerTest {
private static ThreadLocal<Integer> threadLocal = new ThreadLocal<>(); public static void main(String[] args) {
for (int i = 0; i < 2;i++) {
new Thread(new Runnable() {
@Override
public void run() {
int randomValue = new Random().nextInt(9999);
System.out.println(Thread.currentThread().getName() + ", value: " + randomValue);
threadLocal.set(randomValue); new GetA().get();
new GetB().get();
}
}).start();
}
} private static class GetA {
public void get() {
int value = threadLocal.get();
System.out.println("A from " + Thread.currentThread().getName() + ", get data " + value);
}
} private static class GetB {
public void get() {
int value = threadLocal.get();
System.out.println("A from " + Thread.currentThread().getName() + ", get data " + value);
}
}
}

运行的结果如下:

Thread-, value:
Thread-, value:
A from Thread-, get data
A from Thread-, get data
A from Thread-, get data
A from Thread-, get data

友情链接