zoukankan      html  css  js  c++  java
  • 设置线程优先级和开启守护线程

    线程优先级

    public class TestPriority {
        public static void main(String[] args) {
            System.out.println(Thread.currentThread().getName()+"------>"+Thread.currentThread().getPriority());
            MyPriority myPriority = new MyPriority();
            Thread t1 = new Thread(myPriority,"t1");
            Thread t2 = new Thread(myPriority,"t2");
            Thread t3 = new Thread(myPriority,"t3");
            Thread t4 = new Thread(myPriority,"t4");
            Thread t5 = new Thread(myPriority,"t5");
            Thread t6 = new Thread(myPriority,"t6");
    
            //设置优先级再启动
            t1.start();
    
            t2.setPriority(2);
            t2.start();
            t3.setPriority(4);
            t3.start();
            t4.setPriority(6);
            t4.start();
            t5.setPriority(8);
            t5.start();
            t6.setPriority(10);
            t6.start();
        }
    }
    class MyPriority implements Runnable{
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName()+"------>"+Thread.currentThread().getPriority());
        }
    }
    

    通过Thread中的setPriority来设置线程优先级,最高10,最小1。

    开启守护线程

    public class TestDaemon {
        public static void main(String[] args) {
            God god = new God();
            Person person = new Person();
            Thread thread = new Thread(god);
            thread.setDaemon(true);//默认是false为用户线程,设置为true将该线程设置为守护线程
            thread.start();//开启守护线程
            new Thread(person).start();//开启用户线程
        }
    }
    //上帝
    class God implements Runnable{
        @Override
        public void run() {
            while (true) {
                System.out.println("上帝守护着你");
            }
        }
    }
    //凡人
    class Person implements Runnable{
        @Override
        public void run() {
            for (int i = 0; i <100 ; i++) {
                System.out.println("凡人在数数:" + i);
            }
            System.out.println("==========数数完毕!===========");
        }
    }
    

    守护线程不会影响程序,即守护线程不会影响程序的死亡。

    刚刚参加工作,很有很多不懂不会的,发现错误,欢迎指正,谢谢!
  • 相关阅读:
    python生成器和使用gevent操作协程
    python飞机大战
    python控制鼠标键盘+监听键盘
    python生成彩色二维码
    springboot+springcloud+maven相关父子项目创建
    c++求最大公约数
    java8 LocalDateTime
    nginx 代理wss
    vue 全局使用axios
    Vue3.0核心源码解读| 组件渲染:vnode 到真实 DOM 是如何转变的?
  • 原文地址:https://www.cnblogs.com/xd-study/p/13177385.html
Copyright © 2011-2022 走看看