如何中斷一個正在運行的線程

服務器可能需要等待一個請求(request),又或者,一個網絡應用程序可能要等待遠端主機的響應。

import java.net.*;
import java.io.*;
class Example5 extends Thread {
volatile boolean stop = false;
volatile ServerSocket socket;
public static void main( String args[] ) throws Exception {
Example5 thread = new Example5();
System.out.println( “Starting thread…” );
thread.start();
Thread.sleep( 3000 );
System.out.println( “Asking thread to stop…” );
thread.stop = true;
thread.socket.close();
Thread.sleep( 3000 );
System.out.println( “Stopping application…” );
//System.exit( 0 );
}
public void run() {
try {
socket = new ServerSocket(7856);
} catch ( IOException e ) {
System.out.println( “Could not create the socket…” );
return;
}
while ( !stop ) {
System.out.println( “Waiting for connection…” );
try {
Socket sock = socket.accept();
} catch ( IOException e ) {
System.out.println( “accept() failed or interrupted…” );
}
}
System.out.println( “Thread exiting under request…” );
}
}


以下是運行Listing E中代碼後的輸出:

Starting thread…

Waiting for connection…

Asking thread to stop…

accept() failed or interrupted…

Thread exiting under request…

Stopping application…

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章