Thread 与 ThreadLocal
Posted ming-blogs
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Thread 与 ThreadLocal相关的知识,希望对你有一定的参考价值。
@Test
public void testThread() {
Thread thread = Thread.currentThread();
System.out.println("thread:" + thread);
//当前线程 id
System.out.println("threadId:" + thread.getId());
//当前线程名称
System.out.println("threadName:" + thread.getName());
//当前线程状态
System.out.println("threadState:" + thread.getState());
//当前线程优先级
System.out.println("threadPriority:" + thread.getPriority());
//当前线程组名称
System.out.println("threadThreadGroup,Name:" + thread.getThreadGroup().getName());
//当前线程组父类
System.out.println("threadThreadGroup,parent:" + thread.getThreadGroup().getParent());
//当前线程组的最高优先级别
System.out.println("threadThreadGroup,MaxPriority:" + thread.getThreadGroup().getMaxPriority());
System.out.println("threadStackTrace:" + thread.getStackTrace());
System.out.println("ContextClassLoader:" + thread.getContextClassLoader());
}
@Test
public void testThreadLocal() {
ThreadLocal<Object> threadLocal = new ThreadLocal<>();
//默认为 null,初始值为 null
System.out.println(threadLocal.get());
//给当前线程设置值
threadLocal.set("aaa");
System.out.println(threadLocal.get());
threadLocal.set("bbb");
System.out.println(threadLocal.get());
//清空线程值
threadLocal.remove();
}
以上是关于Thread 与 ThreadLocal的主要内容,如果未能解决你的问题,请参考以下文章
具有与 std::thread 不同的线程库的 C++ thread_local
javaThread.Sleep 与 Thread.onSpinWait