ExecutorService.shutdown()应该是在线程执行完毕后,才会去关闭_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > ExecutorService.shutdown()应该是在线程执行完毕后,才会去关闭

ExecutorService.shutdown()应该是在线程执行完毕后,才会去关闭

 2014/4/29 15:34:15  宋建勇  程序员俱乐部  我要评论(0)
  • 摘要:Java多线程-线程池ExecutorService.shutdown什么时候执行importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;importjava.util.concurrent.Semaphore;publicclassSemaphoreTestextendsThread{Semaphoreposition;privateintid;publicSemaphoreTest
  • 标签:Service 执行 在线 线程
Java多线程-线程池ExecutorService.shutdown什么时候执行

class="java">import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreTest extends Thread {
	Semaphore position;
	private int id;

	public SemaphoreTest(int i, Semaphore s) {
		this.id = i;
		this.position = s;
	}

	public void run() {
		try {
			if (position.availablePermits() > 0) {
				System.out.println("顾客[" + id + "]进入厕所,有空位");
			} else {
				System.out.println("顾客[" + id + "]进入厕所,没空位,排队");
			}
			position.acquire();
			System.out.println("【" + id + "】acquire坑位");
			Thread.sleep((int) (Math.random() * 1000));
			System.out.println("【" + id + "】完毕release");
			position.release();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String args[]) {
		ExecutorService pool = Executors.newCachedThreadPool();
		Semaphore position = new Semaphore(2); // 初始化两个空位
		for (int i = 0; i < 5; i++) {
			pool.submit(new SemaphoreTest(i, position));
		}
		System.out.println("开始释放线程池资源");
		pool.shutdown();
		System.out.println("完成释放线程池资源");
		position.acquireUninterruptibly(2);
		System.out.println("如厕完毕,清理厕所");
		position.release(2);
	}
}
上一篇: 携程1500万美元入股途牛 下一篇: 没有下一篇了!
发表评论
用户名: 匿名