• 线程状态、优先级、守护进程


    概述

    img

    使用方法

    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();
    
  • 相关阅读:
    使用60赫兹交流电的关西人
    UI交互细节节选控件使用细则
    PNG button (按钮) files with transparency, for Visual C++ 6.0 and VS2005
    成都第二天:美食
    精力管理与状态转换
    再议“专注”
    成都第一天:印象
    Flash AMF协议
    AS3.0 JSON介绍
    AS3.0 利用AMFPHP与PHP进行通讯 .
  • 原文地址:https://www.cnblogs.com/gbhh/p/13768092.html
Copyright © 2020-2023  润新知