写一个小程序,验证join可抢夺CPU的执行权,高手自动飘过。

package tst.thread;
/**
 * 两个线程一起运算,线程Thread-1前100次循环两个线程同时争抢CPU执行权运行,
 * 执行到Thread-1的第101次循环时,利用join方法,Thread-0从Thread-1抢夺
 * CPU执行权,所以此时接下来Thread-1得等Thread-0执行完才能继续执行,这就是
 * 利用join抢夺CPU执行权,不仅能跟主线程争夺,也能跟其他线程争夺。
 *
 * */
public class JoinDemo {
    public static void main(String[] args) throws InterruptedException {
        Join1 j1 = new Join1(300);
          
        Thread t1 = new Thread(j1);
          
        Join2 j2 = new Join2(300,t1);
        Thread t2 = new Thread(j2);
          
        t1.start();
        t2.start();   
    }
}
class Join1 implements Runnable {
    private int num;
    public Join1(int n) {
        this.num = n;
    }
    public void run() {
        for(int x = 1;x < num;x++) {
            System.out.println(Thread.currentThread().getName() + "---" + x);
        }
    }
}
class Join2 implements Runnable {
    private int num;
    Thread t1;
    public Join2(int n,Thread t1) {
        this.num = n;
        this.t1 = t1;
    }
    public void run() {
        for(int x = 1;x < num;x++) {
            if(x == 100) {
                try {
                    t1.join();         //第101次夺取CPU执行权
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + "---" + x);
        }
    }
}