(Java多线程系列六)join()的用法和线程的优先级

join()的用法和线程的优先级

1、join()的用法

join()作用就是让其他线程处于等待状态

先看一个需求:创建一个线程,子线程执行完毕后,主线程才能执行

public class JoinThreadDemo {

    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("这里是子线程");
                int count = 100;
                while (count > 0) {
                    System.out.println(Thread.currentThread().getName() + "=====" + count);
                    count--;
                }
            }
        });
        thread.start();
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("这里是主线程");
    }

}

Image join

2、设置线程的优先级

在Java线程中,通过一个int priority来控制优先级,范围为1-10,其中10最高,默认值为5。

注:设置了优先级,不代表每次都一定会被执行。只是CPU调度会优先分配

class PriorityThread extends Thread {

    public PriorityThread(String name) {
        this.setName(name);
    }

    @Override
    public void run() {
        System.out.println(getName() + "==========" + getId());
    }
}

public class PriorityThreadDemo {

    public static void main(String[] args) {
        PriorityThread priorityThread1 = new PriorityThread("priority_10");
        PriorityThread priorityThread2 = new PriorityThread("priority_default");
        priorityThread1.setPriority(10);
        priorityThread2.start();
        priorityThread1.start();
    }
}

Image Priority

源码地址

猜你喜欢

转载自www.cnblogs.com/3LittleStones/p/12090645.html