Explain resuming and stopping Threads in java with the help of an exampleprogram.
Question
Explain resuming and stopping Threads in java with the help of an example program.
Solution
In Java, threads are objects that represent a single execution in a program. Java provides built-in support for multithreaded programming, which allows multiple threads to run concurrently within a program.
However, it's important to note that as of Java 2, the Thread
class's suspend
, resume
, and stop
methods are deprecated because they are deadlock-prone. If you need to support these operations, you should manage them at a higher level in your application.
Here's an example of how you might implement this:
class MyThread extends Thread {
private volatile boolean running = true; // Standard way to stop a thread
public void run() {
while (running) {
try {
Thread.sleep(1000); // Simulate doing something
System.out.println("Running...");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println("Thread was interrupted, Failed to complete operation");
}
}
}
// Method to stop the thread
public void stopThread() {
running = false;
}
// Method to resume the thread
public void resumeThread() {
running = true;
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
MyThread myThread = new MyThread();
myThread.start();
Thread.sleep(5000); // Main thread sleeps for 5 seconds
myThread.stopThread(); // Stop the myThread
Thread.sleep(5000); // Main thread sleeps for 5 seconds
myThread.resumeThread(); // Resume the myThread
}
}
In this example, we create a MyThread
class that extends Thread
. Inside the run
method, we have a loop that continues as long as the running
variable is true
. We can stop the thread by calling the stopThread
method, which sets running
to false
, and we can resume the thread by calling the resumeThread
method, which sets running
back to true
.
In the main
method, we start myThread
, let it run for 5 seconds, stop it for 5 seconds, and then resume it.
Similar Questions
Develop a simple java program to start a thread, put the thread to sleep andto resume the thread.
Which method is used to wait for a thread to complete its execution?join()wait()stop()terminate()
Which method is used to create a new thread for long-running tasks in Java?Question 3Answera.newThread()b.startThread()c.runThread()d.invokeLater()
Which method is used to start the execution of a thread in Java? Question 1Answera. run()b. begin()c. start()d. launch()
Which of these methods of Thread class is used to Suspend a thread for a period of time?Select one:a. suspend()b. terminate()c. sleep()d. stop()
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.