- Java.lang.Object.wait(long timeout) Method
- Declaration
- Parameters
- Return Value
- Exception
- Example
- Java wait with timeout
- Enum Constant Summary
- Method Summary
- Methods declared in class java.lang.Enum
- Methods declared in class java.lang.Object
- Enum Constant Detail
- NEW
- RUNNABLE
- BLOCKED
- WAITING
- TIMED_WAITING
- TERMINATED
- Method Detail
- values
- valueOf
- Другие методы класса Thread (sleep, yield…)
Java.lang.Object.wait(long timeout) Method
The java.lang.Object.wait(long timeout) causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
The current thread must own this object’s monitor.
Declaration
Following is the declaration for java.lang.Object.wait() method
public final void wait(long timeout)
Parameters
timeout − the maximum time to wait in milliseconds.
Return Value
This method does not return a value.
Exception
- IllegalArgumentException − if the value of timeout is negative.
- IllegalMonitorStateException − if the current thread is not the owner of the object’s monitor.
- InterruptedException − if another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.
Example
The following example shows the usage of lang.Object.wait() method.
package com.tutorialspoint; import java.util.Collections; import java.util.LinkedList; import java.util.List; public class ObjectDemo extends Object < private List synchedList; public ObjectDemo() < // create a new synchronized list to be used synchedList = Collections.synchronizedList(new LinkedList()); >// method used to remove an element from the list public String removeElement() throws InterruptedException < synchronized (synchedList) < // while the list is empty, wait up to 10 seconds while (synchedList.isEmpty()) < System.out.println("List is empty. "); synchedList.wait(10000); System.out.println("Waiting. "); >String element = (String) synchedList.remove(0); return element; > > // method to add an element in the list public void addElement(String element) < System.out.println("Opening. "); synchronized (synchedList) < // add an element and notify all that an element exists synchedList.add(element); System.out.println("New Element:'" + element + "'"); synchedList.notifyAll(); System.out.println("notifyAll called!"); >System.out.println("Closing. "); > public static void main(String[] args) < final ObjectDemo demo = new ObjectDemo(); Runnable runA = new Runnable() < public void run() < try < String item = demo.removeElement(); System.out.println("" + item); >catch (InterruptedException ix) < System.out.println("Interrupted Exception!"); >catch (Exception x) < System.out.println("Exception thrown."); >> >; Runnable runB = new Runnable() < // run adds an element in the list and starts the loop public void run() < demo.addElement("Hello!"); >>; try < Thread threadA1 = new Thread(runA, "A"); threadA1.start(); Thread.sleep(500); Thread threadA2 = new Thread(runA, "B"); threadA2.start(); Thread.sleep(500); Thread threadB = new Thread(runB, "C"); threadB.start(); Thread.sleep(1000); threadA1.interrupt(); threadA2.interrupt(); >catch (InterruptedException x) < >> >
Let us compile and run the above program, this will produce the following result −
List is empty. List is empty. Opening. New Element:'Hello!' notifyAll called! Closing. Waiting. Hello! Waiting. List is empty. Interrupted Exception!
Java wait with timeout
A thread can be in only one state at a given point in time. These states are virtual machine states which do not reflect any operating system thread states.
Enum Constant Summary
Method Summary
Methods declared in class java.lang.Enum
Methods declared in class java.lang.Object
Enum Constant Detail
NEW
RUNNABLE
Thread state for a runnable thread. A thread in the runnable state is executing in the Java virtual machine but it may be waiting for other resources from the operating system such as processor.
BLOCKED
Thread state for a thread blocked waiting for a monitor lock. A thread in the blocked state is waiting for a monitor lock to enter a synchronized block/method or reenter a synchronized block/method after calling Object.wait .
WAITING
A thread in the waiting state is waiting for another thread to perform a particular action. For example, a thread that has called Object.wait() on an object is waiting for another thread to call Object.notify() or Object.notifyAll() on that object. A thread that has called Thread.join() is waiting for a specified thread to terminate.
TIMED_WAITING
TERMINATED
Method Detail
values
Returns an array containing the constants of this enum type, in the order they are declared. This method may be used to iterate over the constants as follows:
for (Thread.State c : Thread.State.values()) System.out.println(c);
valueOf
Returns the enum constant of this type with the specified name. The string must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)
Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.
Другие методы класса Thread (sleep, yield…)
А теперь немного расскажу про методы sleep, yield, join.
— Это скучно. Я тут нашел вопрос к собеседованию «Чем отличаются методы yield(), sleep(), wait()?». Может расскажешь?
— Не вопрос. Начну с того, что это три совершенно разных метода.
1) sleep(timeout) – останавливает текущую нить (в которой sleep был вызван) на timeout миллисекунд. Нить при этом переходит в состояние TIMED_WAITING. Метод может завершиться раньше, если был установлен флаг isInterrupted.
Thread.sleep(500);
2) yield() – текущая нить «пропускает свой ход». Нить из состояния running переходит в состояние ready, а Java-машина приступает к выполнению следующей нити. Состояния running & ready – это подсостояния состояния RUNNABLE.
Thread.yield();
3) wait(timeout) – это одна из версий метода wait() – версия с таймаутом. Метод wait можно вызвать только внутри блока synchronized у объекта-мютекса, который был «залочен (заблокирован)» текущей нитью, в противном случае метод выкинет исключение IllegalMonitorStateException.
В результате вызова этого метода, блокировка с объекта-мютекса снимается, и он становится доступен для захвата и блокировки другой нитью. При этом нить переходит в состояние WAITING для метода wait() без параметров, но в состояние TIMED_WAITING для метода wait(timeout).
Object monitor = getMonitor(); synchronized(monitor) < … monitor.wait(500); … >
4) join(timeout)
Этого метода не было в твоем вопросе, но он есть в моих планах, так что расскажу и про него. При вызове метода join() или join(timeout) текущая нить как бы «присоединяется» к нити, у объекта которой был вызван данный метод. Текущая нить засыпает и ждет окончания нити, к которой она присоединилась (чей метод join() был вызван).
При этом текущая нить переходит в состояние WAITING для метода join и в состояние TIMED_WAITING для метода join(timeout).
Thread thread = getWorkThread(); thread.join(500);
timeout в методах wait(timeout) и join(timeout) значит, что метод засыпает, ждет чего-то, но не дольше чем timeout миллисекунд. После чего просыпается.
— Такое ощущение, что единственное, что есть общего у этих методов – это timeout. Но делают они совершенно разные вещи.