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

线程优先级

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

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

posted @ 2020-06-22 16:09  小徐学狂  阅读(305)  评论(0编辑  收藏  举报