I want to delay a thread for 5sec ?

Submitted 3 years, 6 months ago
Ticket #218
Views 233
Language/Framework Java
Priority Medium
Status Closed

In java,

    I want to delay the execution of thread for 5 sec 

   Is it possible to delay the execution of code or thread for certain time ?

   If yes ,then please help me out....

 

Submitted on Oct 07, 20
add a comment

2 Answers

Verified

In Java, we can use TimeUnit.SECONDS.sleep() or Thread.sleep() to delay few seconds.

1) TimeUnit :

package com.mkyong;

import java.util.Date;
import java.util.concurrent.TimeUnit;

public class JavaDelayExample {

    public static void main(String[] args) {

        try {

            System.out.println("Start..." + new Date());
            // delay 5 seconds
            TimeUnit.SECONDS.sleep(5);
            System.out.println("End..." + new Date());

            // delay 0.5 second
            //TimeUnit.MICROSECONDS.sleep(500);

			// delay 1 minute
            //TimeUnit.MINUTES.sleep(1);

        } catch (InterruptedException e) {
            System.err.format("IOException: %s%n", e);
        }


    }

}

Thread.sleep :

package com.mkyong;

import java.util.Date;

public class JavaDelayExample2 {

    public static void main(String[] args) {

        try {

            System.out.println("Start..." + new Date());
            // delay 5 seconds
            Thread.sleep(5000);
            System.out.println("End..." + new Date());

        } catch (InterruptedException e) {
            System.err.format("IOException: %s%n", e);
        }


    }

}

Submitted 3 years, 6 months ago

public class Main {

	public static void main(String[] args) {

		System.out.println("Program Started...");
		System.out.println("Current Thread name : " + Thread.currentThread().getName());

		

		try {
			System.out.println("Sleeping for 5 seconds");
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			System.out.println("Thread is interrupted");
		}
		System.out.println("Code delay completed.");

		System.out.println("Program Ended");

	}

}

Submitted 3 years, 6 months ago


Latest Blogs