程序是很簡易的
在本篇文章中
背景中斷(Interrupt)一個線程意味著在該線程完成任務之前停止其正在進行的一切
首先
一些輕率的家伙可能被另一種方法Thread
class Example
boolean stop=false;
public static void main( String args[] ) throws Exception {
Example
System
thread
Thread
System
thread
Thread
System
//System
}
public void run() {
while(!stop){
System
long time = System
while((System
}
}
System
}
}
如果你運行了Listing A中的代碼
Starting thread
Thread is running
Thread is running
Thread is running
Interrupting thread
Thread is running
Thread is running
Thread is running
Stopping application
Thread is running
Thread is running
Thread is running
甚至
真正地中斷一個線程
中斷線程最好的
Listing B
class Example
volatile boolean stop = false;
public static void main( String args[] ) throws Exception {
Example
System
thread
Thread
System
thread
Thread
System
//System
}
public void run() {
while ( !stop ) {
System
long time = System
while ( (System
}
}
System
}
}
運行Listing B中的代碼將產生如下輸出(注意線程是如何有秩序的退出的)
Starting thread
Thread is running
Thread is running
Thread is running
Asking thread to stop
Thread exiting under request
Stopping application
雖然該方法要求一些編碼
到目前為止一切順利!但是
他們都可能永久的阻塞線程
很不幸運
使用Thread
正如Listing A中所描述的
因此
Listing C
class Example
volatile boolean stop = false;
public static void main( String args[] ) throws Exception {
Example
System
thread
Thread
System
thread
thread
Thread
System
//System
}
public void run() {
while ( !stop ) {
System
try {
Thread
} catch ( InterruptedException e ) {
System
}
}
System
}
}
一旦Listing C中的Thread
Starting thread
Thread running
Thread running
Thread running
Asking thread to stop
Thread interrupted
Thread exiting under request
Stopping application
中斷I/O操作
然而
如果你正使用通道(channels)(這是在Java
但是
Listing D
import java
class Example
public static void main( String args[] ) throws Exception {
Example
System
thread
Thread
System
thread
Thread
System
//System
}
public void run() {
ServerSocket socket;
try {
socket = new ServerSocket(
} catch ( IOException e ) {
System
return;
}
while ( true ) {
System
try {
Socket sock = socket
} catch ( IOException e ) {
System
}
}
}
}
很幸運
唯一要說明的是
Listing E
import
import java
class Example
volatile boolean stop = false;
volatile ServerSocket socket;
public static void main( String args[] ) throws Exception {
Example
System
thread
Thread
System
thread
thread
Thread
System
//System
}
public void run() {
try {
socket = new ServerSocket(
} catch ( IOException e ) {
System
return;
}
while ( !stop ) {
System
try {
Socket sock = socket
} catch ( IOException e ) {
System
}
}
System
}
}
以下是運行Listing E中代碼後的輸出
Starting thread
Waiting for connection
Asking thread to stop
accept() failed or interrupted
Thread exiting under request
Stopping application
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27481.html