Knowee
Questions
Features
Study Tools

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

🧐 Not the exact question you are looking for?Go ask a question

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.

This problem has been solved

Similar Questions

Explain Multithreading in Java

what is thread in java

Explain Thread Scheduling with suitable example.

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

1/3

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.