java线程之线程中断的用处
来源:互联网 发布:淘宝首页轮播图片尺寸 编辑:程序博客网 时间:2024/06/05 00:13
引入线程中断用处的背景:
需要以协调的形式来实现任务的取消
一种简单的线程取消方法
public class SimpleThreadCancel {public static void main(String[] args) {CancelableTask task = new CancelableTask();task.start();try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();} // 5秒后结束任务task.cancel();} }class CancelableTask extends Thread {private volatile boolean cancel = false;public void run() {while(!cancel) {try {System.out.println("做任务");Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}System.out.println("任务被取消");}public void cancel() {this.cancel = true;}}
但是这里存在一个问题,假如任务被阻塞住,那么取消动作并不能让while循环退出
例子如下:
生产者不断往队列中存放东西,直到队列满了被阻塞,阻塞在queue.put(),此时执行的取消动作再也不能执行到,程序将一直阻塞,除非队列能够被消耗(即有quue.take()操作被执行)。
public class BlockingCancel {public static void main(String[] args) {BlockingQueue<Object> queue = new ArrayBlockingQueue<>(10);Producer p = new Producer(queue);p.start();try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();} finally {p.cancel();}}}class Producer extends Thread {private BlockingQueue<Object> queue;private volatile boolean cancel;public Producer(BlockingQueue<Object> queue) {this.queue = queue;}@Overridepublic void run() {while(!cancel) {try {this.queue.put("ddd");System.out.println("往队列生产了一个东西,队列size: " + this.queue.size());} catch (InterruptedException e) {e.printStackTrace();}}System.out.println("退出生产");}public void cancel() {this.cancel = true;System.out.println("执行了cancel操作");}}
0 0
- java线程之线程中断的用处
- 中断线程Interrupted的用处
- 【解惑】 中断线程Interrupted的用处
- 【解惑】 中断线程Interrupted的用处
- 【解惑】 中断线程Interrupted的用处
- 中断线程Interrupt与Interrupted的用处
- 【解惑】 中断线程Interrupted的用处
- Java线程的传说(1)——中断线程Interrupted的用处
- Java线程的传说(1)——中断线程Interrupted的用处
- java线程interrupt的用处
- Java线程的中断
- JAVA线程的中断
- java线程的中断
- Java线程的中断
- java线程的中断
- Java 基本功 之中断线程的理解
- Java线程join()方法的用处
- Java线程join()方法的用处
- jQuery选择器总结
- Serv-U FTP Server应用技巧及安全防范
- 将InputStream(输入流)转成String 的方法
- hdu 1166 敌兵布阵
- ZOJ_3195_Design the city(LCA+tarjan)
- java线程之线程中断的用处
- 学习指针型函数和指向函数的指针
- 前五天知识点总结
- 升级win10,提示(RAM)内存不足2G的解决办法,亲测可行
- 微信公众平台开发:进阶篇(Web App开发入门)
- spring 事务传播属性
- SQL中Where与Having的区别 .
- iOS- 给App添加内购& 验证购买iOS8新特性
- static /const