[19/04/08-星期一] 多线程_线程的优先级(Priority) 和 守护线程(Daemon)

一、概念

      1. 处于就绪状态的线程,会进入“就绪队列”等待JVM来挑选。

      2. 线程的优先级用数字表示,范围从1到10,一个线程的缺省优先级是5。

      3. 使用下列方法获得或设置线程对象的优先级。

         int getPriority();

         void setPriority(int newPriority);

      注意:优先级低只是意味着获得调度的概率低。并不是绝对先调用优先级高的线程后调用优先级低的线程。

/**优先级低只是意味着获得调度的概率低。并不是绝对先调用优先级高的线程后调用优先级低的线程.
 * 就是说手拿1000张彩票比1张彩票的中奖概率高点,但不是说1张彩票就不会中奖
 * 优先级范围:数字1-10
 * norm 标准的足额的
 * 3个常量:NORM_PRIORITY=5(所有线程的默认值)
 *         MIN_PRIORITY=1
 *         MAX_PRIORITY=10
 * 
 */
package cn.sxt.thread;

public class Test_0408_ThreadPriority {
    public static void main(String[] args) {
        MyPriority mPriority=new MyPriority();
        Thread t1=new Thread(mPriority,"百度");
        Thread t2=new Thread(mPriority,"阿里");
        Thread t3=new Thread(mPriority,"京东");
        Thread t4=new Thread(mPriority,"腾讯");
        Thread t5=new Thread(mPriority,"网易");
        //设置优先级一定在启动之前,优先级代表调度概率大,不代表绝对的执行的先后顺序
        //即优先级大的也可能正在后边执行,只是大概率在前边执行
        
        t1.setPriority(Thread.MAX_PRIORITY);//常量10
        t2.setPriority(Thread.MIN_PRIORITY);//常量1
        t3.setPriority(Thread.NORM_PRIORITY);//常量5
        t4.setPriority(7);
        t5.setPriority(4);
               
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();       
    }
}
class MyPriority implements Runnable{

    public void run() {
        System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
        
    }
    
}

二、守护线程

/***daemon:守护神
 * 守护线程:是为用户线程服务,jvm(Java虚拟机)停止时不用等待守护线程执行完毕
 * 一般用来做日志等
 * 默认情况下所有线程都是 用户线程,虚拟机需要等所有的用户线程执行完毕才会停止
 * 
 */
package cn.sxt.thread;

public class Test_0408_ThreadDaemon {
    public static void main(String[] args) {
        Time time=new Time();
        People people=new People();
        Thread th=new Thread();
        th.setDaemon(true);//设置用户线程为守护线程,即虚拟机不会等他执行完毕(在控制台输出语句)才停止        
        th.start();
        
        new Thread(people).start();
        
    }
}

class People extends Thread{
    public void run() {
        for (int i = 1; i <= 12; i++) {
            System.out.println(i+"月劳作");
        }    
        System.out.println("一年结束了!");
    }
}
//时间是永恒存在,守护进程,是为用户进程People服务的
class Time extends Thread{
    public void run() {
        for (int i = 1; i <= 24; i++) {//理论上应设置为死循环,因为时间一直都有,但这里设为24
            System.out.println(i+"--时间在流逝");
        }    
    }
    
}

 

posted @ 2019-04-08 20:27  ID长安忆  阅读(355)  评论(0)    收藏  举报