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();
    
  • 相关阅读:
    2、函数
    二者取其一(初遇)_网络流
    P1879 [USACO06NOV]玉米田Corn Fields
    P2831 愤怒的小鸟
    P2296 寻找道路
    序(不知道是什么时候的模拟题)
    P2243 电路维修
    P1273 有线电视网
    P2613 【模板】有理数取余
    P1373 小a和uim之大逃离
  • 原文地址:https://www.cnblogs.com/gbhh/p/13768092.html
Copyright © 2011-2022 走看看