java中sleep()和wait()的区别是什么
作者:RainLight
时间:2023-04-25
来源:互联网
浏览:0
区别说明1、wait()是Object的方法,sleep()是Thread的方法。2、wait()必须采用同步方法,不需要sleep()方法。3、线程在同步方法中执行sleep()方法,不释放monitor锁,wait()方法释放monitor锁。短暂休眠后,sleep()方法会主动退出阻塞,而wait()方法需要在没有指定wait时间的情况下被其他线程中断才能退出阻塞。实例importjava.text.SimpleDateFormat;importjava.util.Date;publicclassT
区别说明
1、wait()是Object的方法,sleep()是Thread的方法。
2、wait()必须采用同步方法,不需要sleep()方法。
3、线程在同步方法中执行sleep()方法,不释放monitor锁,wait()方法释放monitor锁。
短暂休眠后,sleep()方法会主动退出阻塞,而wait()方法需要在没有指定wait时间的情况下被其他线程中断才能退出阻塞。
实例
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestSleepAndWait {
public static void main(String[] args) {
new Thread1().start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread2().start();
}
}
class Thread1 extends Thread{
private void sout(String s){
System.out.println(s+" "+new SimpleDateFormat("HH:mm:ss:SS").format(new Date()));
}
@Override
public void run() {
sout("enter Thread1.run");
synchronized (TestSleepAndWait.class){//wait只能在同步代码块或者同步方法中使用
sout("Thread1 is going to wait");
try {
TestSleepAndWait.class.wait(); // 这里只能使用持有锁TestSleepAndWait.class.wait(),使用其他对象则报错java.lang.IllegalMonitorStateException
} catch (InterruptedException e) {
e.printStackTrace();
}
sout("after waiting, thread1 is going on");
sout("thread1 is over");
}
}
}
class Thread2 extends Thread{
private void sout(String s){
System.out.println(s+" "+new SimpleDateFormat("HH:mm:ss:SS").format(new Date()));
}
@Override
public void run() {
sout("enter Thread2.run");
synchronized (TestSleepAndWait.class){//wait只能在同步代码块或者同步方法中使用
sout("Thread2 is going to notify");
TestSleepAndWait.class.notify(); 这里只能使用持有锁TestSleepAndWait.class
sout("thread2 is going to sleep 10ms");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
sout("after sleeping, thread2 is going on");
sout("thread2 is over");
}
}
}
作者最新文章
傲梅轻松备份
2026-09-16 17:40
photoshop路径工具在哪 怎么用
2026-09-16 13:46
PDF怎么批量添加页码?页码位置和起始页怎么设置?
2026-09-04 14:03
GitLab新手创建项目并推送第一次提交的操作指南
2026-09-03 06:05
PDF怎么编辑修改内容?4招处理方法整理
2026-09-02 18:44
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多
Windows 10
Windows
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式
Windows/macOS/Linux
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















