Java中的线程休眠

Thread.sleep();

阻塞线程休眠,但不释放锁

举例:

static void main() throws InterruptedException {
//        for (int i = 0; i < 10; i++) {
//            Thread.sleep(Duration.ofSeconds(1));
//            //当前线程休眠1秒,阻塞
//            IO.println(i);
//        }

        Thread t1 = new Thread(){
            @Override
            public void run() {
                IO.println("Hello,im thread 1");
                try{
                    Thread.sleep(2000);
                }catch (InterruptedException e){
                    throw new RuntimeException(e);
                }

                IO.println("I'm over");
            }
        };

        t1.start();
    }

另一种写法

//另外一种写法
TimeUnit.SECONDS.sleep(2);

wait和notify

使用wait休眠要使用锁(lock),只能通过锁对象来进行调用,因此只能在同步块或者同步方法中使用,与sleep的区别是wait是释放锁的,也就意味着在此线程阻塞的时候,其他共享同一把锁的线程可以继续执行。

示例如下:新建一个CountTask任务

public class CountTask implements Runnable{
    public byte[] lock = new byte[0];

    @Override
    public void run() {
        synchronized(lock){

            for (int i = 0; i < 10; i++) {
                try {
                    lock.wait(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                IO.println(i);
            }

        }

    }
}

测试类:

public class test02 {
    static void main() {
        CountTask ct = new CountTask();
        Thread t1 = new Thread(ct);
        t1.start();

    }
}

wait有多个重写方法,如果不写入任何参数,则无限期休眠。,示例如下:

修改CountTask任务类:

public class CountTask implements Runnable{
    public byte[] lock = new byte[0];
    public boolean dontWait = false;

    @Override
    public void run() {
        synchronized(lock){

            for (int i = 0; i < 10; i++) {
                try {
                    if(!dontWait){
                        lock.wait();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                IO.println(i);
            }

        }

    }
}

此时若不唤醒,则进程永久阻塞,所以还要添加唤醒条件和唤醒操作,修改测试类:

public class test02 {
    static void main() throws InterruptedException {
        CountTask ct = new CountTask();
        Thread t1 = new Thread(ct);
        t1.start();

        Thread.sleep(2000);
        //休眠2秒之后,将线程唤醒
        synchronized (ct.lock){
            ct.dontWait = true;
            //随机唤醒一个睡眠的线程
            ct.lock.notify();
            //唤醒所有睡眠的线程
            ct.lock.notifyAll();
            
        }

    }
}

此处需要注意,用哪把锁执行的wait,就要用哪把锁唤醒。

THE END
文章版权归Tinsur.cn所有,不允许任何形式的转载
点赞0 分享