不会还不知道线程插队吧!

不会还不知道线程插队吧!

1、yield 线程礼让 让出CPU 让其他线程 执行但执行的时间不确定 也不一定成功

2、join 线程插队 插队一旦插队成功 则肯定先执行完插入完线程所有的任务

package com.company.duoxiancheng.review;

public class ThreadMethod02 {
          
   
    public static void main(String[] args) throws InterruptedException {
          
   

        T3 t3 = new T3();
        t3.start();
        for (int i = 0; i < 20; i++) {
          
   
            Thread.sleep(1000);
            System.out.println("主线程(小弟)吃了"+i+"个包子");
            if (i==5){
          
   
                System.out.println("主线程让小弟让子线程老大吃");
                t3.join();
                System.out.println("子线程老大吃完了");
            }
        }
    }
}
class T3 extends Thread{
          
   
    @Override
    public void run() {
          
   
        for (int i = 0; i <20 ; i++) {
          
   
            try {
          
   
                Thread.sleep(1000);
            } catch (InterruptedException e) {
          
   
                e.printStackTrace();
            }
            System.out.println("子线程(老大)吃了"+i+"包子");
        }
    }
}
经验分享 程序员 微信小程序 职场和发展