Java停止线程
来源:互联网 发布:礼券自助提货系统源码 编辑:程序博客网 时间:2024/06/06 03:55
以生产者消费者模型为例:
生产者:
/** *@function *@modified 2016年1月7日 上午10:01:10 *@author Zhangpengye */package LearnBasic;import java.util.ArrayList;import java.util.List;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class Product{private ExecutorService exec = Executors.newCachedThreadPool();private Consumer consumer = new Consumer();public Product(){consumer.setOutList(list);exec.submit(consumer);}private List<Integer> list = new ArrayList<Integer>();public void addList(Integer e){synchronized (list){list.add(e);list.notify();}}public void close(){consumer.running = false;exec.shutdownNow();}public static void main(String[] args) throws InterruptedException{Product test = new Product();test.addList(1);test.close();}}消费者:
/** *@function *@modified 2016年1月7日 上午9:57:33 *@author Zhangpengye */package LearnBasic;import java.util.List;public class Consumer implements Runnable{private List<Integer> outList = null;public void setOutList(List<Integer> list){this.outList = list;}public boolean running = true;@Overridepublic void run(){System.out.println("线程名称\t" + Thread.currentThread().getName());Thread.currentThread().setName("测试线程");System.out.println("线程名称\t" + Thread.currentThread().getName());while(true == running){try{synchronized (outList){if(true == outList.isEmpty()){System.out.println("qwe");outList.wait();System.out.println("zxc");}else{System.out.println("运行到这里");System.out.println(outList.get(0));outList.remove(0);}}}catch(Exception e){}}System.out.println("程序结束");}}
Tips:
在线程的run循环中加入一个运行标志位:boolean
先关闭运行标志位,此时线程变为驻留状态
再调用exec.shutdownNow(),线程完全退出。
0 0
- Java 线程的停止
- java线程停止【一】
- java线程停止【二】
- java线程停止【三】
- java线程停止【四】
- java 多线程 停止线程
- 如何停止JAVA线程
- Java之线程停止
- 如何停止JAVA线程
- java 线程的停止
- 如何停止JAVA线程
- 如何停止JAVA线程
- java 停止线程
- Java之线程停止
- 如何停止java线程
- java停止线程
- Java之线程停止
- Java---21---停止线程
- QTcpSocket 及 TCP粘包分析
- 使用UncaughtExceptionHandler重启线程
- 再次复习java正则表达式
- Baidu地图的相关开发经验
- Python中的下划线(译文)
- Java停止线程
- 【poj2001】Shortest Prefixes 字典树
- VMware虚拟机上网络连接(network type)的三种模式--bridged、host-only、NAT
- YTU 1009: University
- 记一次Ubuntu突然无法进入系统的经历
- cookie 和session 的区别详解
- web开发中文字符乱码解决集合文GOOD
- fmdb使用
- Activity