Thread的join()方法

关于Thread实例的join代表的含义,先直接看代码和运行结果


public class Main {

    public static void main(String[] args) {

        DemoRunnable demo1 = new DemoRunnable(null);

        Thread t1 = new Thread(demo1,"thread-demo-1");

        DemoRunnable demo2 = new DemoRunnable(t1);
        Thread t2 = new Thread(demo2,"thread-demo-2");
        Thread t3 = new Thread(demo2,"thread-demo-3");
        t1.start();
        t2.start();
        t3.start();

    }


     static class DemoRunnable implements Runnable{
         private Thread t;
        public DemoRunnable(Thread t){
             this.t= t;
         }
        @Override
        public void run() {
            if(t != null){
                try {
                    t.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            for(int i=0; i<10; i++){
                System.out.println(Thread.currentThread().getName()+"   "+i);
            }
        }

     }
}

运行结果:
thread-demo-1 0
thread-demo-1 1
thread-demo-1 2
thread-demo-1 3
thread-demo-1 4
thread-demo-1 5
thread-demo-1 6
thread-demo-1 7
thread-demo-1 8
thread-demo-1 9
thread-demo-3 0
thread-demo-2 0
thread-demo-2 1
thread-demo-3 1
thread-demo-3 2
thread-demo-2 2
thread-demo-3 3
thread-demo-2 3
thread-demo-3 4
thread-demo-2 4
thread-demo-3 5
thread-demo-2 5
thread-demo-3 6
thread-demo-2 6
thread-demo-3 7
thread-demo-2 7
thread-demo-3 8
thread-demo-2 8
thread-demo-3 9
thread-demo-2 9

由此可以分析知:join的意思是,告诉其他的线程,我正在执行,执行完毕后你在执行.join()方法提高了当前线程的优先级,一直抢占着CpU

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值