多线程 interrupt()中断

版权声明:ByRisonBoy https://blog.csdn.net/Rison_Li/article/details/83217925

1、interrupt()和sleep()

代码片段:

public class Main {
	public static void main(String[] args){
		Thread thread = new Thread(new Runnable() {
			public  void run() {
				try {
					Thread.sleep(2000);
					System.out.println("编程大典");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		thread.start();
		thread.interrupt();
	}
}

结果显示:

在线程sleep中,调用其interrupt()会导致其抛出InterruptedException。

其中,interrupt() 方法单独使用不会对线程产生影响。

2、isInterrupted() 根据 Thread.interrupt()的特性做标志法停止子线程

代码显示:

public class Main {
	public static void main(String[] args) throws Exception {
		Thread thread = new Thread(new Runnable() {
			public void run() {
				while (true) {
					//System.out.println("子线程循环终止");
					if(Thread.currentThread().isInterrupted()==true){
						System.out.println("子线程循环终止");
						break;
					}
				}
			}
		});
		thread.start();
		Thread.sleep(1000);
		thread.interrupt();
	}
}

结果显示:

子线程循环终止


 

猜你喜欢

转载自blog.csdn.net/Rison_Li/article/details/83217925
今日推荐