本篇主要看下join和setDaemon方法。
首先,我们先来看这样一个例子:
代码示例1:
package org.mousel.main;
/**
* 我的线程类
* @author lin mouse
*
*/
class MyThread extends Thread {
public void run() {
System.out.println("My Thread started.");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("My Thread ended.");
}
}
/**
* 主线程的类
* @author lin mouse
*
*/
public class ThreadTesting {
public static void main(String[] args) {
System.out.println("Main Thread started.");
MyThread myThread = new MyThread();
myThread.start();
System.out.println("Main Thread ended.");
}
}
输出:
Main Thread started. Main Thread ended. My Thread started. My Thread ended. |
从这个输出信息来看,主线程会提前结束,但是子线程不会被强制终止,一般用在主线程不需要使用子线程产生的数据时。
主线程结束前:
主线程结束后:
代码示例2:
package org.mousel.main;
/**
* 我的线程类
* @author lin mouse
*
*/
class MyThread extends Thread {
public void run() {
System.out.println("My Thread started.");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("My Thread ended.");
}
}
/**
* 主线程的类
* @author lin mouse
*
*/
public class ThreadTesting {
public static void main(String[] args) {
System.out.println("Main Thread started.");
MyThread myThread = new MyThread();
myThread.start();
try {
myThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Main Thread ended.");
}
}
输出:
Main Thread started. My Thread started. My Thread ended. Main Thread ended. |
从这个输出信息来看,使用join方法会使主线程等子线程结束后再结束,一般用在主线程需要使用子线程产生的数据时。
代码示例3:
package org.mousel.main;
/**
* 我的线程类
* @author lin mouse
*
*/
class MyThread extends Thread {
public void run() {
System.out.println("My Thread started.");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("My Thread ended.");
}
}
/**
* 主线程的类
* @author lin mouse
*
*/
public class ThreadTesting {
public static void main(String[] args) {
System.out.println("Main Thread started.");
MyThread myThread = new MyThread();
myThread.setDaemon(true);
myThread.start();
System.out.println("Main Thread ended.");
}
}
输出:
Main Thread started. Main Thread ended. My Thread started. |
从这个输出信息来看,子线程在主线程结束后会被强制终止,这个子线程也叫做Daemon线程。
Daemon线程称为系统监护线程,这是一种专门为系统中其他线程提供服务的线程。最典型的Daemon线程便是实现系统内存垃圾收集的线程。实际上,任何一个线程都可以通过Thread类提供的setDaemon(true)方法而被置为监护线程。另一个方面,程序也可以通过isDaemon()方法来检测和判断某个线程是否为监护线程。监护线程的特点是往往作无限循环运行,以为其他线程服务。当 jvm将退出时,系统中只剩下监护线程,监护线程也将随之结束。