线程的优先级和守护线程
一、设置线程优先级:线程类对象.setPriority(int xxx);
1. 线程优先级范围:1~10。
2. 先设置线程优先级后启动线程。
3. 线程优先级高的说明被CPU调度的概率高,具体调度顺序还是靠CPU调度。
4. 获取线程优先级:
5. 案例:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 
 | package demo.study.ThreadTest;
 public class ThreadPriority {
 public static void main(String[] args) {
 Priority priority = new Priority();
 Thread t1 = new Thread(priority);
 Thread t2 = new Thread(priority);
 Thread t3 = new Thread(priority);
 Thread t4 = new Thread(priority);
 Thread t5 = new Thread(priority);
 System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
 t2.setPriority(4);
 t2.start();
 t3.setPriority(7);
 t3.start();
 t4.setPriority(10);
 t4.start();
 }
 }
 class Priority implements Runnable{
 @Override
 public void run() {
 System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
 }
 }
 
 | 
二、守护(daemon)线程
1. 线程分为用户线程和守护线程。
2. 虚拟机必须确保用户线程执行完毕。
3. 虚拟机不必等待守护线程执行完毕。
4. 创建守护线程:线程类对象.setDaemon(true);参数默认为false代表用户线程。
5. 案例:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 
 | package demo.study.ThreadTest;
 public class ThreadDaeom {
 public static void main(String[] args) {
 Thread t1=new Thread(new You());
 Thread t2=new Thread(new God());
 t2.setDaemon(true);
 t2.start();
 t1.start();
 }
 }
 
 class You implements Runnable{
 @Override
 public void run() {
 for (int i = 0; i < 365; i++) {
 System.out.println("你快乐的活着");
 }
 System.out.println("goodbye");
 }
 }
 
 class God implements Runnable{
 @Override
 public void run() {
 while (true){
 System.out.println("上帝保佑你🙏");
 }
 }
 }
 
 | 
 
    
    
    
    
    
        
        
    
        -------------本文结束感谢您的阅读-------------