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

阻塞多线程的情况有很多种
有可以中断的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和同步方式的阻塞 是不能被中断的。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值