Java停止线程

以生产者消费者模型为例:

生产者:

/**
 *@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;
	
	@Override
	public 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(),线程完全退出。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值