本文共 2866 字,大约阅读时间需要 9 分钟。
setState 的λης statewide method of Thread class in Java determines the current state of a thread. Thread has six possible states: NEW, RUNNABLE, BLOCKED, WAITING, TIME_WAITING, and TERMINATED. This article explains these states, their transitions, and how to control thread states through Thread APIs.
Understanding these states helps in managing concurrent applications effectively.
Upon creating a thread, it enters the NEW state. To switch to runnable, call start(). This transition is immediate upon start() invocation.
Avoid direct state transitions where not possible; follow APIs for state changes.
Example usage of wait() and notify():
public class WaitingExample implements Runnable {public static void main(String[] args) {WaitingExample Reversible = new WaitingExample();Thread t1 = new Thread(Reverable);Thread t2 = new Thread(Reverable);t1.start();t2.start();try {Thread.sleep(3);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("t1:" + t1.getState());System.out.println("t2:" + t2.getState());try {Thread.sleep(1400);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("t1:" + t1.getState());System.out.println("t2:" + t2.getState());}@Overridepublic void run() {method();}private synchronized void method() {try {Thread.sleep(1000);wait();} catch (InterruptedException e) {e.printStackTrace();}}}
Understanding thread states helps manage concurrent applications effectively. Use Thread API methods to control state transitions and design thread-safe code carefully. Avoid over-engineering; keep code simple and efficient.
转载地址:http://bafqz.baihongyu.com/