Java线程yield和join总结

1.yield

  1. 线程礼让(让出cpu),让当前执行的线程暂停,但是不阻塞
  2. 让当前线程从执行状态转为就绪状态,等待cpu重新调度(不一定能礼让成功)
public class TestYeid {
    public static void main(String[] args) throws InterruptedException {
        new testThread("A").start();
        new testThread("B").start();
    }
}

class testThread extends Thread {
    public testThread(String name) {
        super(name);
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + ":processing.");
        Thread.yield();
        System.out.println(Thread.currentThread().getName() + ":end.");
    }
}

执行结果:
image

2.join
合并线程(可以理解为插队),当此线程执行完毕后,再执行其他线程(其他线程阻塞)

public class TestJoin {
    public static void main(String[] args) throws InterruptedException {
        Thread subThread = new Thread(new JoinThread());
        subThread.start();

        for (int i = 0; i < 100; i++) {
            if (i == 10) {
                System.out.println("subThread join!");
                subThread.join();
            } else {
                System.out.println("main Thread:" + i);
            }
        }
    }
}

class JoinThread implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            System.out.println("subThread:" + i);
        }
    }
}

执行结果:

posted @   遥遥领先  阅读(126)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示