Thread wait timeout java

Thread wait timeout java

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.)

Читайте также:  Php get file version

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)

Читайте также:  Java net uri relative path

Этого метода не было в твоем вопросе, но он есть в моих планах, так что расскажу и про него. При вызове метода join() или join(timeout) текущая нить как бы «присоединяется» к нити, у объекта которой был вызван данный метод. Текущая нить засыпает и ждет окончания нити, к которой она присоединилась (чей метод join() был вызван).

При этом текущая нить переходит в состояние WAITING для метода join и в состояние TIMED_WAITING для метода join(timeout).

Thread thread = getWorkThread(); thread.join(500);

timeout в методах wait(timeout) и join(timeout) значит, что метод засыпает, ждет чего-то, но не дольше чем timeout миллисекунд. После чего просыпается.

— Такое ощущение, что единственное, что есть общего у этих методов – это timeout. Но делают они совершенно разные вещи.

Источник

Оцените статью