Export (0) Print
Expand All
Expand Minimize

java.lang.Thread.sleep(long millis)

Visual Studio 2005

Pauses execution of the current thread for the specified time.


public static void sleep(long millis)

Parameters

Parameter Description

millis

The number of milliseconds to sleep.

// thread_sleep2.jsl

public class Program implements Runnable
{
    public static void main(String[] args)
    {
        Program p = new Program();
        p.init();
    }

    public void init()
    {
        try
        {
            // Create a second thread and start it.
            Thread thr2 = new Thread(this);
            System.out.println("Starting " +
                thr2.getName() + "...");
            thr2.start();

            // Sleep for 5 seconds (5000 milliseconds).
            Thread.sleep(5000);

            // Create a third thread and start it.
            Thread thr3 = new Thread(this);
            System.out.println("Starting " +
                thr3.getName() + "...");
            thr3.start();
            
            // Display the number of active threads.  This
            // count includes the main thread.
            System.out.println("Active threads = " +
                Thread.activeCount());

            // Block until the other threads finish.
            thr2.join();
            thr3.join();
        }
        catch (InterruptedException ex)
        {
            System.out.println(ex.toString());
        }
    }

    // Implements Runnable.run()
    public void run()
    {
        for (int i = 0; i < 100000000; i++)
        {
            // Just increment a counter.
            counter++;
        }

        System.out.println(Thread.currentThread().getName() +
            " has finished executing.");
    }

    private int counter = 0;
}

/*
Sample Output:
Starting Thread-0...
Thread-0 has finished executing.
Starting Thread-1...
Active threads = 2
Thread-1 has finished executing.
*/

Community Additions

ADD
Show:
© 2014 Microsoft