The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.lang  [58 examples] > Threads  [11 examples]

e94. Determining When a Thread Has Finished

This example demonstrates a few ways to determine whether or not a thread has returned from its run() method.
    // Create and start a thread
    Thread thread = new MyThread();
    thread.start();
    
    // Check if the thread has finished in a non-blocking way
    if (thread.isAlive()) {
        // Thread has not finished
    } else {
        // Finished
    }
    
    // Wait for the thread to finish but don't wait longer than a
    // specified time
    long delayMillis = 5000; // 5 seconds
    try {
        thread.join(delayMillis);
    
        if (thread.isAlive()) {
            // Timeout occurred; thread has not finished
        } else {
            // Finished
        }
    } catch (InterruptedException e) {
        // Thread was interrupted
    }
    
    // Wait indefinitely for the thread to finish
    try {
        thread.join();
        // Finished
    } catch (InterruptedException e) {
        // Thread was interrupted
    }

 Related Examples
e92. Creating a Thread
e93. Stopping a Thread
e95. Pausing the Current Thread
e96. Pausing a Thread
e97. Determining If the Current Thread Is Holding a Synchronized Lock
e98. Allowing an Application with Live Threads to Exit
e99. Listing All Running Threads
e100. Using a Thread-Local Variable
e101. Getting the Stack Trace of an Exception
e102. Implementing a Work Queue

See also: Arrays    Assertions    Classes    Commands    Numbers    Objects    Strings    System Properties   


© 2002 Addison-Wesley.