Join

合并线程,例如:有两个线程,一个A线程,一个B线程;其中,A线程在运行,但是在运行的一半,使用了Join关键字(B.join),B线程就会加入到A线程,那么A线程就会停止运行,等到B线程执行完成之后,在执行A线程

/**
 * @description: 合并线程Join
 * @author: TateLiao
 * @Date: 2019/3/1
 */
public class JoinDemo1 extends Thread {

    public static void main(String[] args) throws InterruptedException {

        JoinDemo1 joinDemo1 = new JoinDemo1();

        Thread thread = new Thread(joinDemo1);      //新生状态
        thread.start();                             //就绪状态
        //CPU调度运行

        for (int i = 0; i < 100; i++) {
            if (i == 50) {
                thread.join();      //main阻塞
            }
            System.out.println("main..." + i);
        }

    }

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

Yield

暂停线程,虽然功能是这样,但是还得看CPU的调度情况,有可能是让出资源给其它线程执行,也有可能是继续自己执行

/**
 * @description: 暂停线程
 * @author: TateLiao
 * @Date: 2019/3/1
 */
public class YieldDemo1 extends Thread {

    public static void main(String[] args) {
        YieldDemo1 yieldDemo = new YieldDemo1();
        Thread thread = new Thread(yieldDemo);     //新生状态
        thread.start();                             //就绪状态
        //CPU调度执行

        for (int i = 0; i < 1000; i++) {
            if (i%20==0) {
                //暂停自己main
                Thread.yield();
            }
            System.out.println("main..." + i);
        }

    }

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

Sleep

线程睡眠,调用此方法会让调用的线程睡眠,也就进入到阻塞状态,此方法,需要给参数(毫秒数)

/**
 * @description: 多线程Sleep方法
 * @author: TateLiao
 * @Date: 2019/3/1
 */
public class SleepDemo1 {

    /**
     * 倒数十个数,没一秒打印一个
     * @param args
     */
    public static void main(String[] args) throws InterruptedException {

        Date endTime = new Date(System.currentTimeMillis() + 10 * 1000);
        long end = endTime.getTime();

        while (true) {
            System.out.println(new SimpleDateFormat("mm:ss").format(endTime));
            endTime = new Date(endTime.getTime() - 1000);
            Thread.sleep(1000);
            if (end - 10000 > endTime.getTime()) {
                break;
            }
        }

    }

    public void test1() throws InterruptedException {
        int num = 10;

        while (true) {
            System.out.println(num--);
            Thread.sleep(1000);
            if (num <= 0) {
                break;
            }
        }
    }

}