Thread Control in Java: Starting, Stopping, and Restarting
Starting a thread is as simple as creating an instance of the Thread class and calling the start() method. The thread will then execute the code within its run() method.
Stopping a thread, however, is not as straightforward. Once a thread is started, there is no direct way to stop it. Instead, you can use techniques to notify the thread that it should stop executing.
One common approach is to use a boolean flag to indicate whether the thread should continue running. Within the thread's run() method, you can check the flag regularly and terminate the execution when it is set to false.
<code class="java">// Task.java private boolean isRunning = true; @Override public void run() { while (isRunning) { // Perform tasks here } } public void stop() { isRunning = false; }</code>
Restarting a Thread
Restarting a thread means creating a new instance of the Thread class and starting it. This is because threads cannot be reused once they have stopped. However, it's important to note that any data or state maintained by the original thread will not be transferred to the new thread.
Option 1: Create a New Thread
<code class="java">Thread taskThread = new Thread(new Task()); taskThread.start(); // Later, to restart the thread... taskThread = new Thread(new Task()); taskThread.start();</code>
Option 2: Notify and Restart
<code class="java">// Task.java private Object lock = new Object(); @Override public void run() { while (true) { synchronized (lock) { if (shouldStop) { try { lock.wait(); } catch (InterruptedException e) {} } } // Perform tasks here } } public void stop() { synchronized (lock) { shouldStop = true; lock.notify(); } } public void restart() { synchronized (lock) { shouldStop = false; lock.notify(); } }</code>
The above is the detailed content of How to Control Threads in Java: Starting, Stopping, and Restarting?. For more information, please follow other related articles on the PHP Chinese website!