获取主线程Thread.currentThread()

2022-10-12,,

package seday08.thread;

/**
* @author xingsir
* 主线
* 线程提供了一个静态方法这个方法会将运行这个方法的线程返回:static thread currentthread()
* 一个重要的api:threadlocal会使用到它。
*/
public class currentthreaddemo {
/**
* main方法实际上也是靠一个线程运行的。
* @param args
*/
public static void main(string[] args) {
//1.获取到运行main方法的线程
thread main = thread.currentthread();//获取主线程
system.out.println("运行main方法的线程是" + main);//输出
dosome();//main方法里调用dosome方法的线程

//2.匿名内部类,创建一个线程
thread t = new thread() {
public void run() {
thread t = thread.currentthread();//获取主线程
system.out.println("自定义线程:" + t);//输出
dosome();//调用dosome方法的线程
}

};
t.start();//启动线程要调用start
}

public static void dosome() {
// 获取运行dosome方法的线程
thread t1 = thread.currentthread();// 获取主线程
system.out.println("运行dosome方法的线程是:" + t1);//输出
}
}

《获取主线程Thread.currentThread().doc》

下载本文的Word格式文档,以方便收藏与打印。