Thread

sleep

/**
 * Created by gaopj on 2017/8/4.
 */
public class TestThreadSleep implements Runnable {
    int num = 0;
    @Override
    public void run() {
        for (int i=0;i<100;i++) {
            num++;
        }
    }

    public static void main(String[] args) {
        TestThreadSleep ttj = new TestThreadSleep();
        Thread t = new Thread(ttj);
        t.start();
        try {
            t.sleep(100);//
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(ttj.num);
    }
}

join

/**
 * Created by gaopj on 2017/8/4.
 */
public class TestThreadJoin implements Runnable {
    int num = 0;
    @Override
    public void run() {
        for (int i=0;i<100;i++) {
            num++;
        }
    }

    public static void main(String[] args) {
        TestThreadJoin ttj = new TestThreadJoin();
        Thread t = new Thread(ttj);
        t.start();
        try {
            t.join();//线程加入, t 执行完才向后继续执行
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(ttj.num);
    }
}

yield

/**
 * Created by gaopj on 2017/8/4.
 */
public class TestThreadYield implements Runnable {
    int num = 0;
    @Override
    public void run() {
        for (int i=0;i<100;i++) {
            num++;
        }
    }

    public static void main(String[] args) {
        TestThreadYield ttj = new TestThreadYield();
        Thread t = new Thread(ttj);
        t.start();
        while (Thread.activeCount()>1) {
            Thread.yield();
        }
        System.out.println(ttj.num);
    }
}

sleep join yield 预期结果都能正常显示,但sleep是最不合理的.

Last updated

Was this helpful?