优先级
线程的优先级将该线程的重要性传给调度器,尽管CPU处理线程的顺序不确定,但好似Cpu调度器会更倾向于让优先权最高的线程先执行,优先级低的线程仅仅是执行频率较低,不会导致死锁。
public class LiftOff implements Runnable{
private int priority;
public LiftOff(int priority){
this.priority=priority;
}
public void run(){
Thread.currentThread().setPoriority(priority);
System.out.print("haha" +"("+Thread.currentThread().getPriority()+ ")");
Thread.yield();
}
}//创建一个任务类
//使用
public static void main(String[] args){
ExecutorService exec = Executors.newCachedThreadPool();
for(int i =0;i < 5;i++)
exec.execute(new LiftOff(Thread.MIN_PRIORITY));
exec.execute(new LiftOff(Thread.MAX_PRIORITY));
exec.shutdown();
}
Thread.currentThread().getPriority()和Thread.currentThread().setPriority()来读取和修改线程的优先级,Thread.toString()方法可以来打印线程的名称和线程的优先级以及线程所属的组。
尽管JDK有10个优先级,但他与多数操作系统不能映射的很好,比如Windows有7个优先级设定且不固定,一般使用MAX_PRIORITY,NORM_PRIORITY,MIN_PRIORITY。
后台线程:
后台线程是指在程序运行时在后台提供的一种通用服务的线程,并且这种线程不是程序中不可或缺的一部分。当所有非后台线程结束,程序就终止,同时会杀死进程中所有的后台程序,比如main()函数就是一非后台进程。
后台程序用法
public class LiftOff implements Runnable{
private int priority;
public LiftOff(int priority){
this.priority=priority;
}
public void run(){
Thread.currentThread().setPoriority(priority);
System.out.print("haha" +"("+Thread.currentThread().getPriority()+ ")");
Thread.yield();
}
}//创建一个任务类
//使用
public static void main(String[] args){
Thread daemon = new Thread(new LiftOff(MAX_PRIORITY));
demon.setDaemon(true);
daemon.start();
}