Home > Java > javaTutorial > What is the difference between sleep() and wait() in java

What is the difference between sleep() and wait() in java

WBOY
Release: 2023-04-29 08:37:06
forward
2247 people have browsed it

Difference explanation

1. wait() is a method of Object, and sleep() is a method of Thread.

2. Wait() must use the synchronous method, and the sleep() method is not required.

3. The thread executes the sleep() method in the synchronization method without releasing the monitor lock. The wait() method releases the monitor lock.

After a short sleep, the sleep() method will actively exit the blocking, while the wait() method needs to be interrupted by other threads without specifying the wait time to exit the blocking.

Example

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");
}
}
}
Copy after login

The above is the detailed content of What is the difference between sleep() and wait() in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template