×

Sleep Time in Java

Sleep is amethod in java that is related to thread class and it is a concept of multithreading and is used to stop the execution of the current thread a for few seconds.

In java, it is considered as the sleeping time of the thread for which the time up to which the thread remains in sleeping stateand the thread again starts its execution from the position where it has stopped after the completion of sleeping time

The sleep() method is a thread method that is mainly used to pause the process for some seconds and go a thread in the waiting state andhis method does not return anything.

The Sleep() in java is a static method that is called from any contextand it followsthe synchronization.During the process of synchronization, the sleep() method doesn’t release the lock on the object andthe sleep() can be called from outside the Synchronised context.

This method takes sleeping time in milliseconds and here the information is not lost as it again starts the execution from where it stops and the sleep() method sends the current thread into the non-runnable state.

Syntax for Sleep Time Java

There are four variations in the sleep() method. The syntax for sleep time in java is given as:

Public static void sleep(long MLS) throws InterruptedException
Public static void sleep(long MLS) throws IllegalArguementException
Public static void sleep(long MLS, int n) throws InterruptedException
Public static void sleep(long MLS, int n) throws illegal argument exception

In java, the sleep time has the above four types of sleep() methods

Whereas the first two type takes only one argument and the second type takes two arguments

Parameters used in sleep time java or sleep() method are

  • MLS
  • n

mls= this is the first parameter and this MLS parameter represents the time in milliseconds and also it gives the duration at which the thread sleep by the sleep() method.

 n = this is the second parameterthat is passed in the second sleep() method type.It is defined as the extra time up to which the user wants the thread to be sleeping by the sleep() methodand the run of n is from 0 to 999999.

We can understand these two sleep ()method types by seeing the below table

Public static void sleep(long MLS) throws InterruptedException
Or
Public static void sleep(long MLS) throws IllegalArguementException  
Public static void sleep(long MLS,int n) throws InterruptedException
Or
Public static void sleep(long MLS,int n) throws IllegalArguementException  
It takes only one argument or one parameter
It is a native method
Here, we get the implementation of the native method by another programming language     It throws a checked exception                                                           
It takes only twoarguments or twoparameters
It is not a native method that is a non-native method
Here, as we do not have a nativemethodwe get the implementation in java
It also throws a checked exception  

Methods:

The sleep time in java has three types of methods; these methods are known as overloaded methods. They are given as

  • wait()
  • wait(long timeout, int nanoseconds)
  • wait(long timeout)

Constructors:

The constructor for the sleep method is given as

Public static void sleep(long MLS) throws InterruptedException

Examples:

Example of the sleep() method on the custom thread

import java.io.*;
class TestSleepMethod1 extends Thread
{    
 public void run()
{    
for(int i=1;i<4;i++)
{   
try{Thread.sleep(300);
}
catch(InterruptedException e)
{
System.out.println(e);
}    
System.out.println(i);    
  }    
 }    
public static void main(String args[]){    
 TestSleepMethod1 t1=new TestSleepMethod1();    
  TestSleepMethod1 t2=new TestSleepMethod1();    
   t1.start();    
  t2.start();    
 }    
}    

output

1
1
2
2
3
3

Example of the sleep() method on the main thread

import java.lang.Thread;  
import java.io.*;  
public class TestSleepMethod2  
{    
public static void main(String argvs[])  
{   
try
{ 
for (int i = 0; i< 5; i++)  
{    
Thread.sleep(1000);  
System.out.println(i);  
}  
}  
catch (Exception ESPN)   
{  


System.out.println(expn);  
}  
}  
}  

output

0
1
2
3

An example of the sleep() methodis when the sleeping time is negative

import java.lang.Thread;  
import java.io.*;  


public class TestSleepMethod
{  
public static void main(String argvs[])  
{  
try   
{  
for (int i = 0; i< 4; i++)   
{  
Thread.sleep(-400);  
System.out.println(i);  
}  
}  
catch (Exception ESPN)   
{     
System.out.println(expn);  
}  
}  
}  

Output

java.lang.IllegalArgumentException: timeout value is negative

Some important points

  • it is a static method
  • it is the concept of multithreading
  • it is related to thread class
  • it has 4 variations

Related Topics

Cosmic Superclass in Java

The parent class of all Java classes is the Object class. The Java Object class is the parent of all Java classes, whether directly or indirectly. The Object class is...

6 minutes read.

DatabaseMetaData in Java

The Data about another data is called Meta data. The DatabaseMetaData interface has the meta data of the database present in the system. It consists of database product name, total...

2 minutes read.

Java 8 Consumer Interface in Java

The Consumer Interface is used to implement the functional programming in Java. The Consumer Interface indicates a function that accepts a single input and outputs a result. These functions don’t...

2 minutes read.

How to Update Java

As we all know that java can be installed in all operating systems like windows, Linux, macOS. We are available with the java 17 and java 18 versions in the...

3 minutes read.

Difference between Abstract Class and Interface

There is a similarity between abstract class and interface is that we cannot create objects for both of them. But irrespective of this, there are some differences between them, let’s...

2 minutes read.

Level order Traversal of a Binary Tree in Java

In Java, a level order traversal of a tree structure is also referred to as the breadth-first traversal of the binary tree. Regarding the subsequent binary tree: Level order traversal is as...

5 minutes read.

Java Enum vs Class

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four integrators named Club, Diamond,...

7 minutes read.

Method chaining in Java

Method chaining in Java is the act of calling a series of methods one after the other. The sole distinction between it and function Object () constructor chaining is the difference...

3 minutes read.

Advanced Java Viva Questions

One of the more difficult languages available now is Java. Currently, 10 thousand developers worldwide use the programming language, which is rising daily. So, if you're a Java developer, an aspiring...

9 minutes read.

Java IO file not found exception

One of the exception classes offered by the java.io package is FileNotFoundException. An exception is raised when we attempt to access a file that isn't present in the system. It...

4 minutes read.

Java Linters

When it comes to programming, everyone makes mistakes. Errors are bad for developers since they are difficult to handle. But handling as many as possible errors will bring out the...

6 minutes read.

Java Enhanced For Loop (For-each Loop)

JAVA ENHANCED FOR LOOP The enhanced for loop is also called the for-each loop and has some advantages over the regular for loop. A for-each loop is designed to cycle through...

4 minutes read.

How to reverse a linked list in java

The process of reversing a linked list in Java will be covered in this section. One of the most common questions in interviews is about reversing a linked list. If...

11 minutes read.

Two Decimal Places Java

When a double data type is used in Java before a variable, this indicates 15 digits after decimal point. However, there are situations when we only require 2 decimal places...

4 minutes read.

Thread States in Java

An Item's Life Cycle (Thread States) A thread can be in any of the states mentioned above at any given time in Java. They are as follows: New Active I'm blocked or waiting Temporary...

3 minutes read.

Java Tokens

Classes and methods are included in the Java program. The procedures also provide the expressions and statements required to finish a specific operation. Tokens make up the sentences and expressions...

4 minutes read.

How to create a linked list in Java

Introduction: The linked listing is one type of linear statistics shaped like an array. Not like arrays, linked listing factors aren't stored in a contiguous place. The elements have linked...

3 minutes read.

Java Map Generic

Java arrays maintain an ordered collection of things, and the index can be used to access the data (an integer). Unlike HashMap, which stores data as a Key/Value pair. We...

3 minutes read.

Types of Events in Java

One of Java's key ideas is the principle of an event. Events in Java are activities that result in a change in the state or behavior of an object. The...

4 minutes read.

Narcissistic Number in Java

A Narcissistic number is made up of digits that have been added together and raised to powers equal to the number of digits in the original number. In those other...

3 minutes read.