In-depth study of several states of Java threads and their impact on program execution
In Java, a thread is a lightweight execution unit that can be Programs run independently and perform specific tasks. The status of a thread describes the different stages of a thread's execution. Understanding the status of a thread is very important for writing multi-threaded programs and optimizing program performance. This article will delve into several states of Java threads and their impact on program execution, and provide specific code examples.
The several states of Java threads include: NEW (new), RUNNABLE (runnable), BLOCKED (blocked), WAITING (waiting), TIMED_WAITING (timed waiting) and TERMINATED (terminated).
Thread thread = new Thread(() -> { System.out.println("Hello, World!"); });
Thread thread = new Thread(() -> { System.out.println("Hello, World!"); }); thread.start();
public class MyRunnable implements Runnable { private Object lock = new Object(); public void run() { synchronized(lock) { System.out.println("In synchronized block"); // 一些代码 } } public static void main(String[] args) { MyRunnable runnable = new MyRunnable(); Thread thread1 = new Thread(runnable); Thread thread2 = new Thread(runnable); thread1.start(); thread2.start(); } }
In the above code, two threads try to enter the synchronized block at the same time, because the lock is shared, the second thread It will enter a blocking state until the first thread completes execution and releases the lock.
public class MyThread extends Thread { public void run() { synchronized(this) { System.out.println("Waiting for next thread..."); try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread resumed."); } } public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized(thread) { thread.notify(); } } }
In the above code, after the thread enters the waiting state, the main thread wakes up the thread through the notify() method.
public class MyThread extends Thread { public void run() { try { System.out.println("Thread sleeping..."); Thread.sleep(2000); System.out.println("Thread woke up."); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); } }
In the above code, the thread enters the scheduled waiting state by calling the sleep() method, and waits for 2 seconds before being awakened.
In summary, the status of the thread has an important impact on the execution of the program. Understanding the various states and their meaning is crucial to writing efficient multi-threaded programs.
Reference materials:
The above is the detailed content of In-depth study of several states of Java threads and their impact on program execution. For more information, please follow other related articles on the PHP Chinese website!