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


    线程优先级

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

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

    刚刚参加工作,很有很多不懂不会的,发现错误,欢迎指正,谢谢!
  • 相关阅读:
    DS博客作业03--树
    DS博客作业02--栈和队列
    DS博客作业01--线性表
    C语言博客作业05--指针
    C语言博客作业04--数组
    C语言博客作业03--函数
    DS博客作业05--查找
    DS博客作业04--图
    DS博客作业02--栈和队列
    C博客作业05-指针
  • 原文地址:https://www.cnblogs.com/xd-study/p/13177385.html
Copyright © 2020-2023  润新知