zoukankan      html  css  js  c++  java
  • 线程状态、优先级、守护进程

    概述

    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();
    
  • 相关阅读:
    美团数据治理参考
    Ignite(三): Ignite VS Spark
    Ignite(二): 架构及工具
    Sqlserver 计算两坐标距离函数
    Ignite(一): 概述
    IMDG
    锂电池不一致而产生危害
    平均数_中位数_众数在SqlServer实现
    怎样给孩子取一个好名字?搜狗“有名堂”大数据支招
    eclipse导入外部jar包
  • 原文地址:https://www.cnblogs.com/gbhh/p/13768092.html
Copyright © 2011-2022 走看看