`

java中断线程

阅读更多

Thread.stop方法可能中断线程,但不安全,此方法都不会用上,快被淘汰了

 

对线程中的 join, wait, sleep的阻塞进行中断,使用Thread.interrupt()方法退出阻塞, 抛出InterruptedException异常

 

package com.longshine.nio.test;
//中断线程
public class ThreadTest {

	static class TmpThread extends Thread{
		boolean started = true;
		public void run(){
			while(started){
				System.out.println("线程进行中");
				try {
					sleep(10 * 10000);
				} catch (InterruptedException e) {
				}
			}
			System.out.println("线程已中断");
		}
		
		public void stopThead(){
			started = false;
			this.interrupt();
		}
	}
	public static void main(String[] args) throws Exception{
		TmpThread tt = new TmpThread();
		tt.start();
		Thread.sleep(1000);
		tt.stopThead();
	}
}

 

中断IO阻塞 interrupt方法不管用 了,可使用关闭IO的方法中止阻塞,如Socket的InputStream的read()方法,调用read()后关闭Socket,抛出IOException

 

package com.longshine.nio.test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class IOThreadTest {

	public static void main(String[] args) throws Exception{
		new Server().start();
		new Thread(){
			public void run(){
				try {
					new IOThreadTest().work();
				} catch (Exception e) {
				}
			}
		}.start();
		Thread.sleep(2000);
		socket.close();
	}
	
	private static volatile Socket socket;
	
	public void work() throws Exception{
		socket = new Socket();
		socket.connect(new InetSocketAddress("127.0.0.1",8000));
		System.out.println("连接服务器成功");
		//读数据10秒后超时
		socket.setSoTimeout(10000);
		System.out.println("读取数据中");
		try{
			socket.getInputStream().read();
		}
		catch(SocketTimeoutException e){
			System.out.println("超时中断");
		}
		catch(IOException e){
			System.out.println("线程中断");
		}

	}
	
	private static class Server extends Thread{
		
		public void run(){
			try {
				startServer();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		public void startServer() throws Exception{
			ServerSocket serverSocket = new ServerSocket();
			serverSocket.bind(new InetSocketAddress(8000));
			System.out.println("服务启动");
			serverSocket.accept();
			System.out.println("客户端接入");
		}
	}
}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics