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 andto resume the thread.
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:
-
We create a new
Threadobject and override itsrunmethod. This method contains the code that will be executed when the thread is started. -
Inside the
runmethod, we first print "Thread is running...". Then we callThread.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 anInterruptedException, which we catch and print the stack trace of. -
After the thread wakes up, we print "Thread is awake...".
-
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.
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()
Develop a Java program that creates a GUI application for a stopwatch usingSwing. The stopwatch should have start, stop, and reset buttons, and displaythe elapsed time.
Select the correct answerWhich of these method of Thread class is used to Suspend a thread for a period of time?Optionssuspend()terminate()sleep()stop()
Select the correct answerWhich of these method waits for the thread to terminate?Optionsjoin()isAlive()sleep()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.