The following code is easy to find when searching for timeout control of java threads, and there are a large number of results. But can this code get the desired result?
At the beginning, I saw so much and didn't think much about it. I downloaded it directly, but the bug in the program still occurred. I thought there were other problems in the program, and I had to wait for a long time, I found that the original timeout control did not work. I carefully checked the following code and found that this code did not get the desired result.
/**
* 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 ();
}
}
}
I thought of socks's code with time-out control. After a while, I found that its time-out control is directly extended to the native method. It does not seem to be implemented at the java level, it is not easy to want to control another program in one thread in java, so we can only design an alternative mode to work. Is there any other way to go?
Public class TestThreadTimeout extends Thread {
Public static void main (String [] args ){
TestThreadTimeout ttt = new TestThreadTimeout ();
Ttt. start ();
}
Public void run (){
Int timeout = 2000;
TestThread task = new TestThread ();
Task. start ();
Try {
Task. join (timeout );
} Catch (InterruptedException e ){
/* If somebody interrupts us he knowswhat he is doing */
}
If (task. isAlive ()){
Task. interrupt ();
System. out. println ("timeout... ");
Throw new TimeoutException ("xxx ");
} Else {
System. out. println ("No timeout ...");
}
}
}
Class TestThread extends Thread {
Public void run (){
Try {
Thread. sleep (5000 );
System. out. println ("ccccccccccccc ");
} Catch (Exception ex ){
Ex. printStackTrace ();
}
}
// Overwrite the interrupt method if you want the method in run to end normally
Public void interrupt (){
System. out. println ("qqqqqqqqqqqqqqqq ");
}
}