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();
    
  • 相关阅读:
    truncate删除一个分区,测试全局索引是否失效
    DG环境恢复同步遇到报错ORA-00353ORA-00334以及ORA-00600[2619], [47745]
    继承
    智能指针unique_ptr
    explicit
    编译安装python3
    Linux读写执行权限(-r、-w、-x)的真正含义
    nginx入门之编译安装
    vim
    1.yum下载 mysql及授权
  • 原文地址:https://www.cnblogs.com/gbhh/p/13768092.html
Copyright © 2011-2022 走看看