线程的优先级以及守护线程

1.线程的优先级:
线程的优先级指的是,线程的优先级越高越有可能先执行。我们来看几个常用方法:

(1)设置优先级:
public final void setPriority(int newPriority),对于设置优先级的内容可以通过Thread的几个常量来决定:

  • public final static int MIN_PRIORITY = 1;

  • public final static int NORM_PRIORITY = 5;

  • public final static int MAX_PRIORITY = 10;

  • 取得优先级:
    public final int getPriority()
    主线程的优先级为5。

示例代码如下:

class DayThread implements Runnable{

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

}

public class PriThread {
    public static void main(String[] args) {
        DayThread dayThread = new DayThread();
        Thread thread1 = new Thread(dayThread,"myThread_1");
        Thread thread2 = new Thread(dayThread,"myThread_2");
        Thread thread3 = new Thread(dayThread,"myThread_3");
        thread1.setPriority(Thread.MIN_PRIORITY);
        thread2.setPriority(Thread.MAX_PRIORITY);
        thread3.setPriority(Thread.NORM_PRIORITY);
        thread1.start();
        thread2.start();
        thread3.start();
        System.out.println(thread1.getPriority());
    }
}

结果如下:
线程的优先级以及守护线程_第1张图片
可见,优先级比较高的线程有可能会优先执行,但不是一定。

(3) 线程的继承性:
线程的继承性是指,若B线程继承了A线程,那么这两个线程的优先级是相同的。

class DayThread implements Runnable{

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

}

class SonThread extends DayThread{
}

public class PriThread {
    public static void main(String[] args) {
        Thread fatherThread = new Thread(new DayThread(),"Father Thread");
        Thread sonThread = new Thread(new SonThread(),"Son Thread");
        fatherThread.start();
        sonThread.start();
        System.out.println(fatherThread.getPriority());
        System.out.println(sonThread.getPriority());
    }
}

结果如下:
线程的优先级以及守护线程_第2张图片

2.守护线程:

  • Java中有两种线程,一种是守护线程,一种是陪伴线程。Java中启动的线程默认是用户线程,main线程也是用户线程。
  • 可以通过isDaemon()来区分是否为守护线程。
    public final boolean isDaemon()
  • 可以通过setDaemon()来将用户线程设为守护线程。
    public final void setDaemon(boolean on)
  • 垃圾回收线程是典型的守护线程。
  • 守护线程又叫陪伴线程,只要还有一个用户线程在工作,守护线程就一直在工作;当所有用户线程结束之后,守护线程会随着JVM一同停止。
class DaemonThread implements Runnable{

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

}

public class DaemonTest {
    public static void main(String[] args) throws InterruptedException {
        DaemonThread daemonThread = new DaemonThread();
        Thread thread = new Thread(daemonThread,"Daemon Thread");
        thread.setDaemon(true);
        thread.start();
        Thread thread1 = new Thread(daemonThread,"Thread");
        thread1.start();
        thread1.interrupt();
        Thread.sleep(1000);
        System.out.println(Thread.currentThread().getName()+"停止!");
        System.out.println(thread.isDaemon());
    }
}

结果如下:
线程的优先级以及守护线程_第3张图片
在执行过程中,可以看出,当thread1用户线程中断了以后守护线程还没有结束,这是因为main线程还没有结束,守护线程要等到所有的用户线程结束后才会停止工作。

你可能感兴趣的:(线程的优先级以及守护线程)