Java零基础学java之多线程--10线程礼让&Join

线程礼让

  1. 礼让线程,让当前正在执行的线程暂停,但不阻塞
  2. 将线程从运行状态转为就绪状态
  3. 让cpu重新调度,礼让不一定成功!CPU心情
package com.li.thread_state;

//线程礼让,礼让不一定成功,看CPU心情
public class TestThreadYield {
    
    
    public static void main(String[] args) throws InterruptedException {
    
    
        MyYield myYield = new MyYield();
        new Thread(myYield,"a").start();
        new Thread(myYield,"b").start();

    }
}
class MyYield implements Runnable{
    
    

    @Override
    public void run() {
    
    
        System.out.println(Thread.currentThread().getName()+ "-->我开始执行了");
        //Thread.yield();//线程礼让
        System.out.println(Thread.currentThread().getName()+ "-->我结束了");

    }
}







Join

Join合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞

可以想象成插队

package com.li.thread_state;

//测试join
public class TestThreadJoin implements Runnable{
    
    
    @Override
    public void run() {
    
    
        for (int i = 0; i < 100; i++) {
    
    
            System.out.println("都让开,VIP线程来了!" + i);
        }
    }

    public static void main(String[] args) throws InterruptedException {
    
    
        //启动线程
        TestThreadJoin testThreadJoin = new TestThreadJoin();
        Thread thread = new Thread(testThreadJoin);
        thread.start();
        for (int i = 0; i < 200; i++) {
    
    
            if (i == 100) {
    
     //主线程500的时候,让子线程强行插队
                thread.join();

            }
            System.out.println("main主线程" + i);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/l1341886243/article/details/118362982