java主线程结束和子线程结束之间的关系
2017-10-15 21:05
423 查看
情况1:正常情况下,主线程启动了子线程,主线程、子线程各自执行,彼此不受影响。
当你在run一个Java application的时候,这个时候系统会开一个进程。然后这个进程启动了Main线程。Java进程确定虚拟机中没有线程运行的时候,退出进程。或者也可以用System.exit(0);强制退出进程
代码示例如下:参考Thinkingin java代码
[java] view plain copy print?class LiftOff implements Runnable {
Logger logger = LoggerFactory.getLogger(LiftOff.class);
protected int countDown = 10; // Default
private static int taskCount = 0;
private final int id = taskCount++;
public LiftOff() {}
public LiftOff(int countDown) {
this.countDown = countDown;
}
public String status() {
return “#” + id + “(“ +
(countDown > 0 ? countDown : “Liftoff!”) + “), ”;
}
@Override
public void run() {
while(countDown– > 0) {
logger.info(status());
Thread.yield();
}
}
}
public class MainThread{
Logger logger = LoggerFactory.getLogger(MainClass.class);
@Test
public void test(){
Thread t = new Thread(new LiftOff());
t.start();
logger.info(”waiting for liftoff”);
}
}
显示结果:
情况2:需求是主线程执行结束,由主线程启动的子线程都结束
代码如下
[java] view plain copy print?class SimpleDaemons implements Runnable {
Logger logger&nb
4000
sp;= LoggerFactory.getLogger(SimpleDaemons.class);
public void run() {
try {
while (true) {
TimeUnit.MILLISECONDS.sleep(100);
logger.info(”run..”);
}
} catch (InterruptedException e) {
logger.info(”sleep() interrupted”);
}
}
}
public class MainThread {
Logger logger = LoggerFactory.getLogger(MainThread.class);
@Test
public void test() {
for(int i = 0; i < 5; i++) {
Thread daemon = new Thread(new SimpleDaemons());
daemon.setDaemon(true); // Must call before start()
daemon.start();
}
logger.info(”All daemons started”);
try {
TimeUnit.MILLISECONDS.sleep(175);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
运行结果:
情况3:需求是子线程执行结束,主线程等待启动的子线程都结束之后再结束
代码:
[java] view plain copy print?public class IsAliveTest {
public static void main(String args[]) throws Exception {
Thread t = new Thread(new ThreadDemo());
// this will call run() function
t.start();
// waits for this thread to die
t.join();
// tests if this thread is alive
System.out.println(”thread t status = ” + t.isAlive());
System.out.println(”thread main status = ” + Thread.currentThread().isAlive());
}
}
class ThreadDemo implements Runnable {
public void run() {
Thread t = Thread.currentThread();
// tests if this thread is alive
System.out.println(”status = ” + t.isAlive());
try {
t.sleep(3000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
什么情况下一个java thread reach the ‘Die’ state?
From the ThreadAPI, here is a complete list:
1. If the run() method returns. 例如join()之后
2. If an exception is thrown that propagates beyond the run method.
3. If it is a daemon thread and all non-daemonthreads have ‘died’ 非后台线程都结束
4. If the exit method of class Runtime has been called (even at another thread).
实际上,我们对Thread类没有什么控制权,我们几乎不能设置线程的任何状态,我们只能创建任务,并通过某种方式使用线程驱动这个任务
所以,在编写多线程代码的时候,遵循规则就变得非常重要
当你在run一个Java application的时候,这个时候系统会开一个进程。然后这个进程启动了Main线程。Java进程确定虚拟机中没有线程运行的时候,退出进程。或者也可以用System.exit(0);强制退出进程
代码示例如下:参考Thinkingin java代码
[java] view plain copy print?class LiftOff implements Runnable {
Logger logger = LoggerFactory.getLogger(LiftOff.class);
protected int countDown = 10; // Default
private static int taskCount = 0;
private final int id = taskCount++;
public LiftOff() {}
public LiftOff(int countDown) {
this.countDown = countDown;
}
public String status() {
return “#” + id + “(“ +
(countDown > 0 ? countDown : “Liftoff!”) + “), ”;
}
@Override
public void run() {
while(countDown– > 0) {
logger.info(status());
Thread.yield();
}
}
}
public class MainThread{
Logger logger = LoggerFactory.getLogger(MainClass.class);
@Test
public void test(){
Thread t = new Thread(new LiftOff());
t.start();
logger.info(”waiting for liftoff”);
}
}
class LiftOff implements Runnable { Logger logger = LoggerFactory.getLogger(LiftOff.class); protected int countDown = 10; // Default private static int taskCount = 0; private final int id = taskCount++; public LiftOff() {} public LiftOff(int countDown) { this.countDown = countDown; } public String status() { return "#" + id + "(" + (countDown > 0 ? countDown : "Liftoff!") + "), "; } @Override public void run() { while(countDown-- > 0) { logger.info(status()); Thread.yield(); } } } public class MainThread{ Logger logger = LoggerFactory.getLogger(MainClass.class); @Test public void test(){ Thread t = new Thread(new LiftOff()); t.start(); logger.info("waiting for liftoff"); } }
显示结果:
情况2:需求是主线程执行结束,由主线程启动的子线程都结束
代码如下
[java] view plain copy print?class SimpleDaemons implements Runnable {
Logger logger&nb
4000
sp;= LoggerFactory.getLogger(SimpleDaemons.class);
public void run() {
try {
while (true) {
TimeUnit.MILLISECONDS.sleep(100);
logger.info(”run..”);
}
} catch (InterruptedException e) {
logger.info(”sleep() interrupted”);
}
}
}
public class MainThread {
Logger logger = LoggerFactory.getLogger(MainThread.class);
@Test
public void test() {
for(int i = 0; i < 5; i++) {
Thread daemon = new Thread(new SimpleDaemons());
daemon.setDaemon(true); // Must call before start()
daemon.start();
}
logger.info(”All daemons started”);
try {
TimeUnit.MILLISECONDS.sleep(175);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class SimpleDaemons implements Runnable { Logger logger = LoggerFactory.getLogger(SimpleDaemons.class); public void run() { try { while (true) { TimeUnit.MILLISECONDS.sleep(100); logger.info("run.."); } } catch (InterruptedException e) { logger.info("sleep() interrupted"); } } } public class MainThread { Logger logger = LoggerFactory.getLogger(MainThread.class); @Test public void test() { for(int i = 0; i < 5; i++) { Thread daemon = new Thread(new SimpleDaemons()); daemon.setDaemon(true); // Must call before start() daemon.start(); } logger.info("All daemons started"); try { TimeUnit.MILLISECONDS.sleep(175); } catch (InterruptedException e) { e.printStackTrace(); } } }
运行结果:
情况3:需求是子线程执行结束,主线程等待启动的子线程都结束之后再结束
代码:
[java] view plain copy print?public class IsAliveTest {
public static void main(String args[]) throws Exception {
Thread t = new Thread(new ThreadDemo());
// this will call run() function
t.start();
// waits for this thread to die
t.join();
// tests if this thread is alive
System.out.println(”thread t status = ” + t.isAlive());
System.out.println(”thread main status = ” + Thread.currentThread().isAlive());
}
}
class ThreadDemo implements Runnable {
public void run() {
Thread t = Thread.currentThread();
// tests if this thread is alive
System.out.println(”status = ” + t.isAlive());
try {
t.sleep(3000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class IsAliveTest { public static void main(String args[]) throws Exception { Thread t = new Thread(new ThreadDemo()); // this will call run() function t.start(); // waits for this thread to die t.join(); // tests if this thread is alive System.out.println("thread t status = " + t.isAlive()); System.out.println("thread main status = " + Thread.currentThread().isAlive()); } } class ThreadDemo implements Runnable { public void run() { Thread t = Thread.currentThread(); // tests if this thread is alive System.out.println("status = " + t.isAlive()); try { t.sleep(3000L); } catch (InterruptedException e) { e.printStackTrace(); } } }测试结果
什么情况下一个java thread reach the ‘Die’ state?
From the ThreadAPI, here is a complete list:
1. If the run() method returns. 例如join()之后
2. If an exception is thrown that propagates beyond the run method.
3. If it is a daemon thread and all non-daemonthreads have ‘died’ 非后台线程都结束
4. If the exit method of class Runtime has been called (even at another thread).
实际上,我们对Thread类没有什么控制权,我们几乎不能设置线程的任何状态,我们只能创建任务,并通过某种方式使用线程驱动这个任务
所以,在编写多线程代码的时候,遵循规则就变得非常重要
相关文章推荐
- java主线程结束和子线程结束之间的关系
- java主线程结束和子线程结束之间的关系
- java主线程结束和子线程结束之间的关系
- Java学习笔记45:Java 线程与主线程之间的变量关系
- Java学习笔记45:Java 线程与主线程之间的变量关系
- Java多线程之线程的五种状态以及状态之间的关系
- 线程:Java主线程等待子线程结束
- Java 并发编程中的 CountDownLatch 锁用于多个线程同时开始运行或主线程等待子线程结束
- java基础:进程和线程之间的关系
- 安卓基础:Handler, Looper,消息队列,线程及主线程之间的关系
- pthread_create主线程与创建的新线程之间退出关系
- java主线程结束和子线程结束之间的关系
- 主线程与子线程之间退出关系
- java中主线程等待所有子线程结束
- Java - 线程的基本状态以及状态之间的关系?
- 【Linux学习】pthread_create主线程与创建的新线程之间退出关系
- 线程退出【Linux学习】pthread_create主线程与创建的新线程之间退出关系
- C#/.NET主线程与子线程之间的关系
- Java主线程如何等待子线程执行结束(转)
- 【Linux学习】pthread_create主线程与创建的新线程之间退出关系