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
原创粉丝点击