【狂神说Java】线程礼让,线程插队

yield方法

  • 礼让线程,让当前正在执行的线程暂停,但不阻塞
  • 将线程从运行状态转为就绪状态
  • 让cpu重新调度,礼让不一定成功。
public class TestYield {
    public static void main(String[] args) {
        new Thread(new MyYield1(), "A").start();
        new Thread(new MyYield2(), "B").start();

    }
}

class MyYield1 implements Runnable {
    @Override
    public void run() {
        System.out.println("开始A");
        Thread.yield();// 暂停,让cpu重新调度
        System.out.println("结束A");
    }
}

class MyYield2 implements Runnable {
    @Override
    public void run() {
        System.out.println("开始B");
        System.out.println("结束B");
    }
}

join方法

  • join合并线程,待此线程执行完成后,再执行其他线程(执行时,其他线程阻塞)
public class JoinTest {
    public static void main(String[] args) {
        Thread thread = new Thread(new MyJoin(),"a");
        thread.start(); // 线程启动
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName()+"--> 第" +i);
            if (i == 5){// main线程中断,a线程介入
                try {
                    thread.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

class MyJoin implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName()+"-->Join, 第"+i);
        }
    }
}

执行结果如图:

posted @ 2021-09-16 16:22  Jie7  阅读(97)  评论(0)    收藏  举报