threadLocal一般使用
package com.tulingxueyuan.tl;
import com.oracle.webservices.internal.api.databinding.DatabindingMode;
/**
* @author zsj
* @date 2023/10/12 0012 23:12
*/
public class ChineseThreadLocal {
static ThreadLocal<String> threadLocal =new ThreadLocal<>();
static ThreadLocal<Integer> intThreadLocal =new ThreadLocal<>();
public void getThread(){
Thread[] threads=new Thread[4];
for (int i = 0; i <threads.length ; i++) {
new TaskThread(i,"中国富强伟大").start();
}
}
public static class TaskThread extends Thread{
String des ;
int id;
public TaskThread(int id,String des){
this.id = id;
this.des = des;
}
@Override
public void run() {
String name = Thread.currentThread().getName();
threadLocal.set(des+":"+id);
if (id == 3) {
intThreadLocal.set(id);
}
System.out.println(name+":"+threadLocal.get());
System.out.println(name+":"+intThreadLocal.get());
}
public static void main(String[] args) {
ChineseThreadLocal local = new ChineseThreadLocal();
local.getThread();
}
}
}
执行结果(多次执行结果都不相同)
ThreadLocal内存溢出的Demo
在没有加入ThreadLocal时
package com.tulingxueyuan.tl;
import com.tulingxueyuan.tools.SleepTools;
import java.util.concurrent.*;
/**
* @author zsj
* @date 2023/10/12 0012 23:41
*/
public class ThreadLocalOOM {
private static final int TASK_LOOP_SIZE = 500;
final static ThreadPoolExecutor poolExecutor =new ThreadPoolExecutor(4,4,10,TimeUnit.SECONDS,new LinkedBlockingDeque<>());
static class LocalVariable {
private byte[] a = new byte[1024*1024*5];/*5M大小的数组*/
}
public sta