在 Java 中,我们什么时候可以调用某个线程的 wait() 和 wait(long) 方法?
只要对某个对象调用 wait() 方法,就会使当前线程等待,直到另一个线程为该对象调用 notify() 或 notifyAll() 方法,而 wait(long timeout) 会使当前线程等待,直到另一个线程为该对象调用 notify() 或 notifyAll() 方法,或指定超时时间已过。
wait()
在以下程序中,当对某个对象调用 wait() 时,该线程将从运行状态进入等待状态。它等待其他线程调用 notify() 或 notifyAll() 才能进入可运行状态,这将形成死锁。
示例
class MyRunnable implements Runnable {
public void run() {
synchronized(this) {
System.out.println("In run() method");
try {
this.wait();
System.out.println("Thread in waiting state, waiting for some other threads on same object to call notify() or notifyAll()");
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
}
public class WaitMethodWithoutParameterTest {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable, "Thread-1");
thread.start();
}
}
输出
In run() method
wait(long)
在以下程序中,当对某个对象调用 wait(1000) 时,该线程将从运行状态进入等待状态,即使在调用 notify() 或 notifyAll() 之后,在超时时间过后的线程,仍将从等待状态进入可运行状态。
示例
class MyRunnable implements Runnable {
public void run() {
synchronized(this) {
System.out.println("In run() method");
try {
this.wait(1000);
System.out.println("Thread in waiting state, waiting for some other threads on same object to call notify() or notifyAll()");
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
}
public class WaitMethodWithParameterTest {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable, "Thread-1");
thread.start();
}
}
输出
In run() method Thread in waiting state, waiting for some other threads on same object to call notify() or notifyAll()
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP