java 多线程(threadlocal)

时间:2023-12-05 08:56:32
package com.fredric.demo;

import java.util.Random;

public class App {

    public static class MyRunnable1 implements Runnable {
//ThreadLocal是一个线程局部变量
private ThreadLocal<String> threadlocal
= new ThreadLocal<String>(); private int tmp; public void run() {
//threadlocal 包含方法:
//set:创建一个线程本地变量
//remove:移除该本地变量
//get:获取该本地变量的值
//在hibernate中被用于本地session管理
threadlocal.set("Name:"+new Random().nextInt(10));
int i = new Random().nextInt(10); System.out.println("set tmp: " + i); tmp = i;
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " : " + threadlocal.get() + " " + tmp);
}
} public static void main(String[] args) {
MyRunnable1 r = new MyRunnable1();
Thread t1 = new Thread(r,"thread1");
Thread t2 = new Thread(r,"thread2");
t1.start();
t2.start(); /*
输出如下:局部变量没有改变,而Threadlocal每个线程有自己独立的副本
set tmp: 0
set tmp: 1
thread1 : Name:3 1
thread2 : Name:4 1 */
}
}