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 @ 2023-05-18 00:47  遥遥领先  阅读(96)  评论(0编辑  收藏  举报