Java监听主线程是否运行中
时间: 2023-02-15 10:42:35 浏览: 48
Java可以使用Thread.isAlive()方法来检测主线程是否运行中。例如:
```
public class MainThreadDemo {
public static void main(String[] args) throws InterruptedException {
Thread mainThread = Thread.currentThread();
System.out.println("Before starting the new thread, main thread is alive? " + mainThread.isAlive());
Thread anotherThread = new AnotherThread();
anotherThread.start();
System.out.println("After starting the new thread, main thread is alive? " + mainThread.isAlive());
anotherThread.join();
System.out.println("After finishing the new thread, main thread is alive? " + mainThread.isAlive());
}
}
class AnotherThread extends Thread {
@Override
public void run() {
System.out.println("In the new thread");
}
}
```
在运行上述代码后,输出结果应该是这样的:
```
Before starting the new thread, main thread is alive? true
After starting the new thread, main thread is alive? true
In the new thread
After finishing the new thread, main thread is alive? true
```