并发中断多种阻塞线程的情况代码

阻塞多线程的情况有很多种
有可以中断的sleep()方式。
有不可以中断的IO和同步方式。

java.util.concurrent 提供 ExecutorService.submit()来执行单个线程 返回一个可执行的上下文Future<?>通过Future 可以对阻塞进行中断 Future.cancle(true);

package com.text;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

//sleep 可中断的阻塞线程
class SleepBlocked implements Runnable {

	public void run() {
		try {
			TimeUnit.SECONDS.sleep(100);
		} catch (InterruptedException e) {
			System.out.println("InterruptedException");
		}
		System.out.println("Exiting SleepBlocked.run()");
	}

}

// IO 阻塞线程
class InputBlocked implements Runnable {

	private InputStream in;

	public InputBlocked(InputStream is) {
		this.in = is;
	}

	public void run() {
		try {
			System.out.println("Waiting for read()");
			in.read();
		} catch (IOException e) {
			if (Thread.currentThread().isInterrupted()) {
				System.out.println("Interrupted from blocked I/O");
			} else {
				throw new RuntimeException(e);
			}
		}
		System.out.println("Exiting InputBlocked.run");
	}
}
//同步阻塞线程
class SynchronizedBlocked implements Runnable {

	private synchronized void f() {
		while (true) {
			Thread.yield();
		}
	}

	public SynchronizedBlocked() {
		new Thread() {
			public void run() {
				f();
			}
		}.start();
	}

	public void run() {
		System.out.println("Trying call the f()");
		f();
		System.out.println("Exiting SynchronizedBlocked.run()");
	}
}

public class Interrupting {

	private static ExecutorService exec = Executors.newCachedThreadPool();

	static void test(Runnable r) throws InterruptedException {
		Future<?> t = exec.submit(r);
		TimeUnit.SECONDS.sleep(100);
		System.out.println("Interrupting " + r.getClass().getName());
		t.cancel(true);
		System.out.println("Interrupt sent to " + r.getClass().getName());
	}

	public static void main(String[] args) throws InterruptedException {
		test(new SleepBlocked());
		test(new InputBlocked(System.in));
		test(new SynchronizedBlocked());
		TimeUnit.SECONDS.sleep(3);
		System.out.println("Aborting with System.exit(0)");
		System.exit(0);
	}
}



下面是打印出来的结果:
Interrupting com.text.SleepBlocked
Interrupt sent to com.text.SleepBlocked
Exiting SleepBlocked.run()
Waiting for read()
Interrupting com.text.InputBlocked
Interrupt sent to com.text.InputBlocked
Trying call the f()
Interrupting com.text.SynchronizedBlocked
Interrupt sent to com.text.SynchronizedBlocked
Aborting with System.exit(0)
可见IO和同步方式的阻塞 是不能被中断的。

你可能感兴趣的:(线程)