Knowee
Questions
Features
Study Tools

Develop a simple java program to start a thread, put the thread to sleep andto resume the thread.

Question

Develop a simple java program to start a thread, put the thread to sleep and to resume the thread.

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

Solution

Sure, here is a simple Java program that starts a thread, puts it to sleep, and resumes it:

public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread() {
            public void run() {
                try {
                    System.out.println("Thread is running...");
                    Thread.sleep(2000); // Put thread to sleep for 2 seconds
                    System.out.println("Thread is awake...");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        thread.start(); // Start the thread
    }
}

Here's how it works:

  1. We create a new Thread object and override its run method. This method contains the code that will be executed when the thread is started.

  2. Inside the run method, we first print "Thread is running...". Then we call Thread.sleep(2000), which puts the thread to sleep for 2000 milliseconds (or 2 seconds). If the thread is interrupted while it's sleeping, it will throw an InterruptedException, which we catch and print the stack trace of.

  3. After the thread wakes up, we print "Thread is awake...".

  4. Finally, we call thread.start() to start the thread.

Please note that Java does not support explicitly resuming a thread after it has been put to sleep. The thread will automatically resume once the sleep duration has passed or the thread is interrupted. If you need more control over the execution of the thread, you might want to look into using wait and notify instead.

This problem has been solved

Similar Questions

Explain resuming and stopping Threads in java with the help of an exampleprogram.

Select the correct answerWhich of these method wakes up the first thread that called wait()?Optionsstart()notify()wake()notifyAll()

Select the correct answerWhich of this method can be used to make the main thread to be executed last among all the threads?Optionsjoin()sleep()stop()call()

Select the correct answerWhich of the following will ensure the thread will be in running state?Optionsyield()wait()Thread.killThread()notify()

Select the correct answerWhich of these method wakes up all the threads?Optionsstart()notify()wakeAll()notifyAll()

1/1

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.