多线程中yield和join的作用

join的作用在源码中就一句话Waits for this thread to die

其实这句话有点不准确,它少了一个主语:父线程。完整的表述应该是parent thread waits for this thread to die。意思就是调用这个线程的父线程会处于阻塞状态知道这个线程执行完。比如:

public static void main(String[] args) throws InterruptedException
    {
         Thread thread = new Thread(new Runnable()
        {
            
            public void run()
            {
                try
                {
                    Thread.sleep(1000);
                }
                catch (InterruptedException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println("new Thread");
            }
        });
       thread.start();
       thread.join();
       System.out.println("main thread");
    }

这里打印信息是 new Thread 

                         main Thread

线程thread的父线程是主线程,因此thread调用join()方法后主线程阻塞知道thread执行完

 

 

 

yield方法作用其实也可以用一句话来表述:表示愿意让出当前调度的使用权

源码解释的第一段是:A hint to the scheduler that the current thread is willing to yield

      its current use of a processor. The scheduler is free to ignore this hint.

暗示调度者这个线程愿意让出对当前调度的使用,调度者可以无视这个暗示。

讲道理对于计算机来说准确性很重要我只能说对这个方法很无语

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值