
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Concurrency Sleep Method
The sleep function
This sleep function is used to ensure that the currently executing thread goes to sleep for a specific amount of milliseconds which is passed as a parameter to the function. The thread stops executing for that number of milliseconds.
Let us see an example
Example
import java.lang.*; public class Demo implements Runnable{ Thread my_t; public void run(){ for (int i = 0; i < 3; i++){ System.out.println(Thread.currentThread().getName()+ " " + i); try{ Thread.sleep(100); } catch (Exception e){ System.out.println(e); } } } public static void main(String[] args) throws Exception{ Thread my_t = new Thread(new Demo()); my_t.start(); Thread my_t2 = new Thread(new Demo()); my_t2.start(); } }
Output
Thread-0 0 Thread-1 0 Thread-0 1 Thread-1 1 Thread-0 2 Thread-1 2
A class named Demo implements the Runnable class. A new thread is defined. Next, a ‘run’ function is defined that iterates over a set of elements and gets the name of the thread using the ‘getName’ function. In the try block, the sleep function is called on the thread and the catch block prints the exception, if any occurs.
The main function creates two new instances of the Thread and it is begun using the ‘start’ function. Here also, elements are iterated over and the yield function is called on the thread.