其他分享
首页 > 其他分享> > 优先级和守护线程

优先级和守护线程

作者:互联网

 

优先级

package com.lei.state;

//测试线程优先级
public class TestPriority {
    public static void main(String[] args) throws InterruptedException {
        //主线程默认优先级
        System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());

        MyPriority myPriority=new MyPriority();

        Thread t1=new Thread(myPriority);
        Thread t2=new Thread(myPriority);
        Thread t3=new Thread(myPriority);
        Thread t4=new Thread(myPriority);
        Thread t5=new Thread(myPriority);
        Thread t6=new Thread(myPriority);

        //先设置优先级在启动
        t1.start();
        //不设置延迟的话cpu跑得太快,不会按照优先级
        Thread.sleep(2000);
        t2.setPriority(1);
        t2.start();

        t3.setPriority(4);
        t3.start();

        t4.setPriority(Thread.MAX_PRIORITY);//MAX_PRIORITY=10
        t4.start();

        //错误
//        t5.setPriority(-1);
//        t5.start();
//
//        t6.setPriority(11);
//        t6.start();

    }
}

class MyPriority implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
    }
}

 

守护线程

package com.lei.state;

import com.sun.xml.internal.stream.util.ThreadLocalBufferAllocator;

//测试守护线程
//上帝守护你
public class TestDaemon {
    public static void main(String[] args) {
        God god = new God();
        You you = new You();

        Thread thread = new Thread(god);
        thread.setDaemon(true);//默认是false表示用户线程,正常的线程都是用户线程

        thread.start();

        new Thread(you).start();
    }
}


//上帝
class God implements Runnable{

    @Override
    public void run() {
        while(true){
            System.out.println("上帝保护你");
        }
    }
}

//你
class You implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 36500; i++) {
            System.out.println("你一生都开心的活着");
        }
        System.out.println("=====GoodBye World!=====");
    }
}

 

标签:myPriority,优先级,Thread,start,线程,new,public,守护
来源: https://www.cnblogs.com/evelei/p/16140027.html