×

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

How to check if date is valid in Java?

In this article, you will acknowledge about how to verify if a date is valid or not. For this you will learn the approach, you will be able to write...

3 minutes read.

PriorityBlockingQueue Class in Java

What is the Queue? An abstract data structure like Stacks is a queue. A queue is open on both ends. Data is always pushed to one end, called enqueue, and removed...

4 minutes read.

List of Constants in Java

In this tutorial, we are going to deal with constants available in Java.Every programming language has its constants. Similarly, Javaalso has got constants of its own. In this tutorial, we will...

6 minutes read.

India Map Pattern in Java

India Map Pattern is the pattern we'll code now using Java, as demonstrated. We will use a star in Java to print our India map.The specialty is that we will only...

4 minutes read.

String Manipulation in Java

String Manipulation in Java In Java, string manipulation is a common task performed by programmer. Java String class provides many built-in functions that are used to manipulate string. The manipulation of...

4 minutes read.

Statements in java

What is Statement in java: A statement in java is an instruction that explains what will happen based on the condition. Types of java statements: There are different statements in java Expression statementDeclaration statementControl...

2 minutes read.

Java Boolean hashCode() Method

The hashCode() method of Boolean class returns the hash code for the specified Boolean object or the given Boolean value. Syntax public int hashCode()public int hashCode(boolean value) Parameters The parameter ‘value’ represents the value...

2 minutes read.

How to Calculate Week Number From Current Date in Java?

The WeekFields class's weekOfMonth() method is utilized to return the field for access the week of a month based on this WeekFields. If the first day of the month is a...

3 minutes read.

Resultset in java

Resultset: A result set is an interface that is present in the package java.sql and the resultset is used to store the data that are returned from the database table after...

5 minutes read.

Economical number in Java

Economical number is said to be economically efficient if the number of digits after prime factorization of the original number with their powers is less than the number of digits...

3 minutes read.

Zigzag Traversal of Binary Tree in Java

In this article, you will be acknowledged about the zigzag traversal of binary tree in java and the approaches or ways in which the zigzag traversal can be done. Zigzag Traversal A...

10 minutes read.

Thread Concept in Java

What is a Thread? A subprocess that is lightweight in Java is known as a thread. It is the smallest unit of a process. For the running of multiple tasks parallelly...

3 minutes read.

Coin change problem in dynamic programming

In this tutorial, we will understand a popular problem called the coin changeproblem through dynamic programming. This problem checks the logical and critical thinking ability of the person. Dynamic Programming...

5 minutes read.

Vigesimal in Java

A number system with a base of 20 is known as the vigesimal in Java. A base-20 (base-score) numeric system, often known as a vigesimal system, is centered on the twenty...

4 minutes read.

Stack Program in Java

Stack Program in Java The Stack class is part of the collection framework that inherits the Vector class. Thus, the Stack class can also be called a subclass of the Vector...

5 minutes read.

Java Integer toOctalString() method

The toOctalString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 8. Syntax public static String toOctalString (int  i) Parameters The parameter ‘i’ represents...

1 minute read.

Java Throw and Throws Keyword

Exceptions in Java enable us to construct high-quality programs where faults are checked at compile time rather than run time and where we may define unique exceptions that make code...

6 minutes read.

Java vs DotNET

Before understanding the differences between DotNET and Java, one must know about Java and DotNET. Java Java is a general-purpose programming language that is class-based and object-oriented, with minimal implementation dependencies. Regardless of...

9 minutes read.

String Palindrome Program in Java

String Palindrome Program in Java The palindrome is a string, phrase, word, number, or other sequences of characters that can be read in both directions i.e. forward (left to right) and...

11 minutes read.

Zig Zag star and Number Pattern in Java

We covered many Java pattern applications in the preceding part. We will write Java applications for zigzag star and number patterns in this part. Printing Zig Zag Number Pattern Steps Print one...

3 minutes read.