Java中sleep()和wait()方法讲解

本文详细讲解了Java中多线程的sleep()和wait()方法,包括各自的方法汇总、案例使用,并对比了它们的区别与联系。sleep()用于线程暂停,而wait()则涉及线程间的通信,且wait()会释放锁。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


一、sleep()方法及案例使用

  • 方法汇总
public static void sleep(long millis)throws InterruptedException
/*使当前正在执行的线程以指定的毫秒数暂停(暂时停止执行),
具体取决于系统定时器和调度程序的精度和准确性。 
线程不会丢失任何显示器的所有权。 
*/
public static void sleep(long millis,int nanos)throws InterruptedException
/*
导致正在执行的线程以指定的毫秒数加上
指定的纳秒数来暂停(临时停止执行),
这取决于系统定时器和调度器的精度和准确性。 
线程不会丢失任何显示器的所有权。 
*/
  • 简单举例
public class testSleepAndWait {
    public static void main(String[] args) {
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    long start=System.currentTimeMillis();
                    Thread.sleep(2000);
                    long end=System.currentTimeMillis();
                    System.out.println("thread1运行结束,用时"+(end-start)/1000+"秒");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                    long start=System.currentTimeMillis();
                    long end=System.currentTimeMillis();
                    System.out.println("thread2运行结束,用时"+(end-start)+"秒");
            }
        });
        thread1.start();
        thread2.start();
        /*
        控制台输出:
        thread2运行结束,用时0秒
        thread1运行结束,用时2秒
         */
    }
}

二、wait()方法及案例使用

  • 方法汇总
public final void wait()throws InterruptedException
/*
导致当前线程等待,直到另一个线程调用该对象的
notify()方法或notifyAll()方法。 换句话说,这个方法的行为
就好像简单地执行呼叫wait(0) 。 
*/
public final void wait(long timeout)throws InterruptedException
/*导致当前线程等待,直到另一个线程调用此对象的
notify()方法或notifyAll()方法,或指定的时间已过。 
当前的线程必须拥有该对象的显示器。 
*/

public final void wait(long timeout,int nanos)throws InterruptedException
/*
导致当前线程等待,直到另一个线程调用此对象的
notify()方法或notifyAll()方法,或其他一些线程中断当前线程,
或一定量的实时时间。 这种方法类似于一个参数的wait方法,
但它允许对放弃之前等待通知的时间进行更精细的控制。 
以纳秒为单位的实时数量由下式给出: 
 1000000*timeout+nanos
 */
  • 简单举例
class MyThread {
    private   String s="ABCDEFGH";
    private static volatile int index=0;
    public synchronized  void printJ(String threadName) throws InterruptedException {
        while (index%2==0){//只要当前索引为偶数就等待
           this.wait();
        }
        if(index>=s.length()){
            return;
        }
        System.out.println(threadName+"输出"+s.charAt(index));
        index++;
        this.notify();//释放锁
    }
    public synchronized  void printO(String threadName) throws InterruptedException {

        while (index%2==1){//只要当前索引为偶数就等待
            this.wait();
        }
        if(index>=s.length()){
            return;
        }
        System.out.println(threadName+"输出"+s.charAt(index));
        index++;
        this.notify();
    }
}
public class testSleepAndWait {
    public static void main(String[] args) throws InterruptedException {
        MyThread myThread = new MyThread();
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 3; i++) {
                    try {
                        myThread.printJ(Thread.currentThread().getName());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 3; i++) {
                    try {
                        myThread.printO(Thread.currentThread().getName());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread1.start();
        thread2.start();
        /*
        控制台输出:
        Thread-1输出A
        Thread-0输出B
        Thread-1输出C
        Thread-0输出D
        Thread-1输出E
        Thread-0输出F
         */
    }
}

三、sleep()和wait()区别与联系

  • 相同点
    • sleep()和wait()都可以暂停正在执行点的线程。
  • 不同点
    • sleep()通常被用于线程的暂停执行;wait()通常用于线程之间的通信
    • sleep()是Thread类的静态方法;wait()是Object类的方法
    • sleep()不释放锁;wait()释放锁
    • sleep()方法被调用后,当睡眠指定的时间后,线程会自动苏醒;
      wait()方法被调用后,直到另一个线程调用此对象的notify()方法或notifyAll()方法,线程才会苏醒。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值