优先级函数
线程的优先级将该线程的重要性传给调度器,尽管CPU处理线程的顺序不肯定,但好似Cpu调度器会更倾向于让优先权最高的线程先执行,优先级低的线程仅仅是执行频率较低,不会致使死锁。this
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。线程
后台线程:code
后台线程是指在程序运行时在后台提供的一种通用服务的线程,而且这种线程不是程序中不可或缺的一部分。当全部非后台线程结束,程序就终止,同时会杀死进程中全部的后台程序,好比main()函数就是一非后台进程。进程
后台程序用法get
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(); }