Monday 7 May 2012

Java Thread sleep Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
Thread class sleep method example. This example shows you how to use sleep method.

Thread class sleep method example.public static void sleep(long millis) throws InterruptedException Causes the currently executing thread to sleep for the specified number of milliseconds, 
subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors. 


Here is the code

/**
 * @ # Sleep1.java
 * A class repersenting use to Sleep(long) method of Thread class in java.lang package 
 */
public class Sleep1 implements Runnable {

    Thread th;

    public void run() {
        for (int i = 0; i <= 1; i++) {

            System.out.println(Thread.currentThread().getName() + " " + i);
            try {
                //thread to sleep for the specified number of milliseconds
                Thread.sleep(100);
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }

    public static void main(String[] args) throws Exception {
        Thread th = new Thread(new Sleep1());
        th.start();

        Thread th1 = new Thread(new Sleep1());
        th1.start();
    }
}
Output:
------------
Thread-1 0
Thread-2 0
Thread-1 1
Thread-2 1

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...