Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Example – Terminate a thread

Java Examples - Terminating a Thread

Java Examples Java Examples

Java originally provided the stop() method in Thread to terminate a thread, but this method is unsafe and is generally not recommended.

This article introduces interrupting a thread with the interrupt method.

Using the interrupt method to interrupt a thread can be divided into two cases:

In the first case, when the interrupt method is used, the sleep method throws an InterruptedException; in the second case the thread exits directly. The code below demonstrates using the interrupt method in the first case.

ThreadInterrupt.java file

public

class

ThreadInterrupt

extends

Thread

{

public

void

run

(

)

{

try

{

sleep

(

50000

)

;

//

Delay 50 seconds

}

catch

(

InterruptedException

e

)

{

System

.

out

.

println

(

e

.

getMessage

(

)

)

;

}

}

public

static

void

main

(

String

[

]

args

)

throws

Exception

{

Thread

thread

=

new

ThreadInterrupt

(

)

;

thread

.

start

(

)

;

System

.

out

.

println

(

"

Press any key within 50 seconds to interrupt the thread!

"

)

;

System

.

in

.

read

(

)

;

thread

.

interrupt

(

)

;

thread

.

join

(

)

;

System

.

out

.

println

(

"

The thread has exited!

"

)

;

}

}

The output of the above code is:


在50秒之内按任意键中断线程!

sleep interrupted
线程已经退出!

Java Examples Java Examples