线程休眠—sleep方法

Thread.sleep(ms):当前线程进入Time—Wait状态,并等待指定时间。

与wait的区别:wait只能用于同步块中,wait释放锁。

class MyThread implements Runnable {
    public void run() {
        int i = 0;
        while(i < 6) {
            System.out.println(Thread.currentThread() + " a = " + i);
            i++;
            Thread.yield();
        }
    }
}
public class Demo1 {

    public static void main(String[] args) throws Exception {
        Thread t1 = new Thread(new MyThread(),"t1");
        Thread t2 = new Thread(new MyThread(),"t2");
        t1.start();
        t2.start();
        Thread.sleep(1);
        System.out.println(Thread.currentThread());
    }

}
posted @ 2020-03-15 22:23  卑微芒果  Views(1865)  Comments(0Edit  收藏  举报