1. 程式人生 > 實用技巧 >執行緒狀態、優先順序、守護程序

執行緒狀態、優先順序、守護程序

概述

使用方法

getState()

setPriority(Thread.MAX_PRIORITY);

例項

狀態

/**
 * 執行緒狀態
 *  new -》 runnable -》 TIMED_WAITING -》 TERMINATED
 */
public class ThreadState {
    public static void main(String[] args) {
        Thread t1 = new Thread(()-> {
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("/////////////////");
        });

        Thread.State state = t1.getState();
        System.out.println(state); //new
        t1.start();
        state = t1.getState();
        System.out.println(state); //run

        while (state != Thread.State.TERMINATED){
            try {
                Thread.sleep(1000);
                state = t1.getState();
                System.out.println(state);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

優先順序

/**
 * 執行緒優先順序
 */
public class ThreadPriority {
    public static void main(String[] args) {
//        主執行緒優先順序
        System.out.println(Thread.currentThread().getName()+"=====>>"+Thread.currentThread().getPriority());
        Thread t1 = new Thread(new MyPriority());
        Thread t2 = new Thread(new MyPriority());
        Thread t3 = new Thread(new MyPriority());
        Thread t4 = new Thread(new MyPriority());
        t1.setPriority(Thread.MAX_PRIORITY);
        t2.setPriority(3);
        t3.setPriority(2);
        t4.setPriority(1);

        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}

class MyPriority implements Runnable{

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

守護執行緒

守護執行緒是指為其他執行緒服務的執行緒。在JVM中,所有非守護執行緒都執行完畢後,無論有沒有守護執行緒,虛擬機器都會自動退出。

因此,JVM退出時,不必關心守護執行緒是否已結束。

Thread t = new MyThread();
t.setDaemon(true);
t.start();