Java thread timeout setting method

Source: Internet
Author: User
Tags sleep thread class

Method 1

In this example, ExecutorService is used to replace Timer to control the timeout of a thread. The code is as follows:

The code is as follows: Copy code


Package com. stackoverflow. q2275443;

Import java. util. concurrent. Callable;
Import java. util. concurrent. ExecutorService;
Import java. util. concurrent. Executors;
Import java. util. concurrent. Future;
Import java. util. concurrent. TimeUnit;
Import java. util. concurrent. TimeoutException;

Public class Test {
Public static void main (String [] args) throws Exception {
ExecutorService executor = Executors. newSingleThreadExecutor ();
Future future = executor. submit (new Task ());

Try {
System. out. println ("Started ..");
System. out. println (future. get (3, TimeUnit. SECONDS ));
System. out. println ("Finished! ");
} Catch (TimeoutException e ){
System. out. println ("Terminated! ");
        }

Executor. shutdownNow ();
    }
}

Class Task implements Callable {
@ Override
Public String call () throws Exception {
Thread. sleep (4000); // www.111cn.net Just to demo a long running task of 4 seconds.
Return "Ready! ";
    }
}

Set
System. out. println (future. get (3, TimeUnit. SECONDS ));
Change
System. out. println (future. get (5, TimeUnit. SECONDS ));
The thread will be correctly executed
You can intercept the timeout in the catch (TimeoutException e) block.

Method 2

Class 1: daemon thread class

The code is as follows: Copy code

/**
* This thread sets a timeout value.
* After the thread starts running, the time-out period is specified,
* This thread will throw an unchecked exception and notify the program that calls this thread to time out.
* You can call the cancel method of this class to cancel the timer before the timeout period ends.
* @ Author solonote
*/
Public class TimeoutThread extends Thread {
/**
* Timer timeout
*/
Private long timeout;
/**
* Whether the timing is canceled
*/
Private boolean isCanceled = false;
/**
* Exception thrown when the timer times out
*/
Private TimeoutException timeoutException;
/**
* Constructor
* @ Param timeout specifies the timeout time
*/
Public TimeoutThread (long timeout, TimeoutException timeoutErr ){
Super ();
This. timeout = timeout;
This. timeoutException = timeoutErr;
// Set this thread as the daemon thread

This. setDaemon (true );
}
/**
* Cancel timing
*/
Public synchronized void cancel ()
{
IsCanceled = true;
}
/**
* Start the timeout timer.
*/
Public void run ()
{
Try {
Thread. sleep (timeout );
If (! IsCanceled)
Throw timeoutException;
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
}
Note: The TimeoutException in Class 1 is the user-defined class below, not java. util. concurrent. TimeoutException in java.

Class 2. Throw an exception class that inherits RuntimeException because the run method cannot throw a detected exception.

Public class TimeoutException extends RuntimeException {
/**
* Serialization number
*/
Private static final long serialVersionUID =-8078853655388692688L;
Public TimeoutException (String errMessage)
{
Super (errMessage );
}
}
Usage:

// Initialization timeout class

TimeoutThread t = new TimeoutThread (5000, new TimeoutException ("timeout "));
Try {
T. start ();
... The program segment to detect timeout ....
T. cancel ();
} Catch (TimeoutException e)
{
... Processing timeout...
}
TimeoutException can be changed to another non-checked exception class.

Method description:

This method enables the thread to manage the timeout by itself and manage the timeout of a piece of code. You can provide a solution within the method.

However, it should be noted that the timeout time of this method is not the running time of the current thread, but the timer starts timing the system running time.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.