1. 后台线程:处于后台运行,任务是为其余线程提供服务。也称为“守护线程”或“精灵线程”。JVM的垃圾回收就是典型的后台线程。
特色:若全部的前台线程都死亡,后台线程自动死亡。
设置后台线程:Thread对象setDaemon(true);
setDaemon(true)必须在start()调用前。不然出现IllegalThreadStateException异常;
前台线程建立的线程默认是前台线程;
判断是不是后台线程:使用Thread对象的isDaemon()方法;
spa
而且当且仅当建立线程是后台线程时,新线程才是后台线程。线程
例子:对象
class Daemon implements Runnable{
public void run() {
for (int i = 0; i < 200; i++) {
System.out.println("Daemon -->" + i);
}
}
}
public class DaemonDemo {
public static void main(String[] args) {
/*Thread cThread = Thread.currentThread();
System.out.println(cThread.isAlive());
//cThread.setDaemon(true);
System.out.println(cThread.isDaemon());*/
Thread t = new Thread(new Daemon());
System.out.println(t.isDaemon());
for (int i = 0; i < 10; i++) {
System.out.println("main--" + i);
if(i == 5){
t.setDaemon(true);
t.start();
}
}
}
}
get
2,线程的优先级:it
每一个线程都有优先级,优先级的高低只和线程得到执行机会的次数多少有关。
并不是线程优先级越高的就必定先执行,哪一个线程的先运行取决于CPU的调度;
默认状况下main线程具备普通的优先级,而它建立的线程也具备普通优先级。
Thread对象的setPriority(int x)和getPriority()来设置和得到优先级。
MAX_PRIORITY :值是10
MIN_PRIORITY :值是1
NORM_PRIORITY :值是5(主方法默认优先级)
io
注意:每一个线程默认的优先级都与建立他的父线程的优先级相同,在在默认的状况下,class
main线程具备普通优先级,由main线程建立的子线程也具备普通优先级后台
例子:垃圾回收
class Priority implements Runnable{
public void run() {
for (int i = 0; i < 200; i++) {
System.out.println("Priority-- " + i);
}
}
}
public class PriorityDemo {
public static void main(String[] args) {
/**
* 线程的优先级在[1,10]之间
*/
Thread.currentThread().setPriority(3);
System.out.println("main= " + Thread.currentThread().getPriority());
/*
* public final static int MIN_PRIORITY = 1;
* public final static int NORM_PRIORITY = 5;
* public final static int MAX_PRIORITY = 10;
* */
System.out.println(Thread.MAX_PRIORITY);
//===============================================
Thread t = new Thread(new Priority());
for (int i = 0; i < 200; i++) {
System.out.println("main" + i);
if(i == 50){
t.start();
t.setPriority(10);
}
System.out.println("-------------------------"+t.getPriority());
}
}
}
方法