首页 > 编程语言 > 详细

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

时间:2019-12-24 12:42:29      阅读:89      评论:0      收藏:0      [点我收藏+]

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("这里是主线程");
    }

}

技术分享图片

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();
    }
}

技术分享图片

源码地址

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

原文:https://www.cnblogs.com/3LittleStones/p/12090645.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!