线程礼让yield和线程的强制执行join

少废话,直接看例子:

注意礼让不一定都成功。

关于yield的使用方式,例子如下:

package com.lipu.state;

public class TestYield {
    public static void main(String[] args) {
        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的使用方式,例子如下:

package com.lipu.state;
//测试join方法
public class TestJoin implements Runnable {
    @Override
    public void run(){
        for (int i = 0; i < 10; i++) {
            System.out.println("线程VIP来了");
        }
    }
    public static void main(String[] args) throws InterruptedException {
        
        //启动我们的线程
        TestJoin testJoin = new TestJoin();
        Thread thread = new Thread(testJoin);
        thread.start();
        //主线程
        for (int i = 0; i < 100; i++) {
            if (i==20){
                thread.join();//插队
            }
            System.out.println("main"+i);
            
        }
    }
}

输出结果:

 使用join线程会被强制插入

package com.lipu.state;
//测试join方法
public class TestJoin implements Runnable {
@Override
public void run(){
for (int i = 0; i < 10; i++) {
System.out.println("线程VIP来了");
}
}
public static void main(String[] args) throws InterruptedException {

//启动线
TestJoin testJoin = new TestJoin();
Thread thread = new Thread(testJoin);
thread.start();
//线
for (int i = 0; i < 100; i++) {
if (i==20){
thread.join();//插队
}
System.out.println("main"+i);

}
}
}

原文地址:https://www.cnblogs.com/lipu12281/p/12201499.html