• 设置线程优先级和开启守护线程


    线程优先级

    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("==========数数完毕!===========");
        }
    }
    

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

    刚刚参加工作,很有很多不懂不会的,发现错误,欢迎指正,谢谢!
  • 相关阅读:
    欧几里得算法及扩展欧几里得(含)
    RP
    P1734_最大约数和
    The 2017 ACM-ICPC Asia East Continent League Final记录
    【数据结构】bzoj1651专用牛棚
    【数据结构】bzoj1455罗马游戏
    【数据结构】bzoj1636/bzoj1699排队
    【数据结构】bzoj3747Kinoman
    【计算几何】奇特的门
    Topcoder SRM 608 div1 题解
  • 原文地址:https://www.cnblogs.com/xd-study/p/13177385.html
Copyright © 2020-2023  润新知