多线程sleep与wait的区别

本文详细解析并发编程中wait与notify机制的作用与实现原理,通过实例代码演示线程间如何通过同步锁进行交互与状态通知。

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


package com.huawei.interview;

public class Thread1 implements Runnable{

public void run() {
synchronized (MultiThread.class){
System.out.println("enter thread1!");
System.out.println("thread1 is waiting");
try{
MultiThread.class.wait();
}catch (Exception e) {
e.printStackTrace();
}
System.out.println("thread1 is going on");
System.out.println("thread1 is being over");
};
}

}




package com.huawei.interview;

public class Thread2 implements Runnable{

public void run() {
synchronized (MultiThread.class){
System.out.println("enter thread2");
System.out.println("thread2 notify other thread can release wait status");
MultiThread.class.notify();
System.out.println("thread2 is sleeping for ten ms");
try{
Thread.sleep(10);
}catch (Exception e) {
e.printStackTrace();
}
System.out.println("thread2 is going on");
System.out.println("thread2 is being over");
};
}

}




package com.huawei.interview;

public class MultiThread {
public static void main(String[] args) {

new Thread(new Thread1()).start();
try{
Thread.sleep(10);
}catch (Exception e) {
e.printStackTrace();
}
new Thread(new Thread2()).start();
}
}



运行结果:

enter thread1!
thread1 is waiting
enter thread2
thread2 notify other thread can release wait status
thread2 is sleeping for ten ms
thread2 is going on
thread2 is being over
thread1 is going on
thread1 is being over



解释:
sleep就是正在运行的线程主动让出cpu,cpu去执行其他线程,在sleep指定的时间过后,cpu

才会回到这个线程上继续运行,如果当前线程进入了同步锁,sleep方法并不会释放锁,即使

当前线程使用了sleep让出了cpu,但其他被同步锁挡住了的线程也无法得到执行。wait是指一

个已经进入了同步锁的线程内,让自己暂时让出同步锁,以便其他正在等待此锁的线程可以得

到同步锁并运行,只有其他线程调用了notify方法(notify方法并不会释放锁,只是告诉调用

过wait的线程可以参与获得锁的竞争了,但是不会马上得到锁,因为锁还在其他线程手中,别

人还没释放)调用wait方法的线程就会解除wait状态,程序可以再次获得锁后继续向下运行
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值