yield(),join()以及总结sleep,join,yield,wait

(一):yield()
在这里插入图片描述
(二): join()
在这里插入图片描述

对于第一点举个栗子:

public class  SysController {
    public static void main(String[] args) throws InterruptedException{
       Thread thread0 = new Thread(()-> {
           System.out.println(Thread.currentThread().getName()+"Thread0 completed");
       });
       Thread thread1 = new Thread(()->{
           System.out.println(Thread.currentThread().getName()+"Thread1 started");
           System.out.println(Thread.currentThread().getName()+"Thread1 sleeping for seconds");
           try{
              Thread.sleep(2000);
           }catch (InterruptedException e){
               e.printStackTrace();
           };
           System.out.println(Thread.currentThread().getName()+"Thead1 completed");
       });
       //线程1
        thread0.start();
        //线程1调用join()
        thread0.join();
        thread1.start();
    }

}

输出:
在这里插入图片描述
解释:
在主线程(main)中执行thread0时调用 thread0.join();时,会让主线程停止,先让thread0执行完后main线程在执行thread1。这就验证了1和2
又一个栗子:

public class  SysController {
    public static void main(String[] args) throws InterruptedException{
       Thread thread1 = new Thread(()-> {
           System.out.println(Thread.currentThread().getName()+"Thread1 completed");
       });
       Thread thread0 = new Thread(()->{
           try{
             thread1.join();
           }catch (InterruptedException e){
               e.printStackTrace();
           };
           System.out.println(Thread.currentThread().getName()+"Thead0 completed");
       });
       //线程1
        thread0.start();
        //线程1调用join()
        //thread0.join();
        thread1.start();
    }

输出:
在这里插入图片描述
解释:
thread1.join(); 导致main线程先让Thread1执行完,在执行Thread0,同时验证了第2点。

总结:
在这里插入图片描述

发布了163 篇原创文章 · 获赞 9 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_41987908/article/details/103609142