java后台进程和线程优先级


 1. 后台线程:处于后台运行,任务是为其他线程提供服务。也称为“守护线程”或“精灵线程”。JVM的垃圾回收就是典型的后台线程。
特点:若所有的前台线程都死亡,后台线程自动死亡。
设置后台线程:Thread对象setDaemon(true);
setDaemon(true)必须在start()调用前。否则出现IllegalThreadStateException异常;
前台线程创建的线程默认是前台线程;
判断是否是后台线程:使用Thread对象的isDaemon()方法;

并且当且仅当创建线程是后台线程时,新线程才是后台线程。

例子:



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();
}
}
}
}



2,线程的优先级:

每个线程都有优先级,优先级的高低只和线程获得执行机会的次数多少有关。
并非线程优先级越高的就一定先执行,哪个线程的先运行取决于CPU的调度;
默认情况下main线程具有普通的优先级,而它创建的线程也具有普通优先级。
Thread对象的setPriority(int x)和getPriority()来设置和获得优先级。
MAX_PRIORITY :值是10
MIN_PRIORITY :值是1
NORM_PRIORITY :值是5(主方法默认优先级)


注意:每个线程默认的优先级都与创建他的父线程的优先级相同,在在默认的情况下,

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());
}
}
}

 

posted on 2013-11-14 21:20  新一  阅读(1556)  评论(0编辑  收藏  举报

导航