java,辨别子线程、主线程
程序员文章站
2022-06-10 23:26:49
...
public class Main {
public static void main(String[] args) throws Exception {
Thread t = new Thread(new Worker());//Thread-0
t.start();//Thread-0
//Thread.sleep(200);//main线程,与Thread.currentThread().sleep(200);同义
System.out.println("Thread.sleep(200)");
Thread.currentThread().sleep(200);//main线程
t.interrupt();//Thread-0
System.out.println("t.getName():" + t.getName());//Thread-0
System.out.println("2 Thread.currentThread().getName():" + Thread.currentThread().getName());//main线程
System.out.println("Main thread stopped.");
}
public static class Worker implements Runnable {
public void run() {
System.out.println("Worker started.");
try {
System.out.println("1 Thread.currentThread().getName():" + Thread.currentThread().getName());//Thread-0
Thread.sleep(500);//Thread-0
} catch (InterruptedException e) {
Thread curr = Thread.currentThread();//Thread-0
System.out.println("curr.getName():" + curr.getName());//Thread-0
}
System.out.println("Worker stopped.");
}
}
}
输出:
Thread.sleep(200)
Worker started.
1 Thread.currentThread().getName():Thread-0
t.getName():Thread-0
curr.getName():Thread-0
2 Thread.currentThread().getName():main
Worker stopped.
Main thread stopped.
-----------------------
main()中的Thread是主线程,
从Runnable实现的线程、从Thread继承的线程是子线程,
--------------------------
Worker started.不是最先输出的,因为线程start是就绪状态,run是运行状态,start会异步调用run方法,
参考:https://blog.csdn.net/Alex___Zhao/article/details/75137390 漫谈操作系统9 -- 线程运行状态
https://blog.csdn.net/tornado886/article/details/4524346 Thread的run()与start()的区别