首页 > JAVA > 使用固定大小的ThreadPool

使用固定大小的ThreadPool

2009年12月27日 admin 发表评论 阅读评论

java.util.concurrent包提供了很多并发的工具类,下面这段代码是一个简单的线程池的样例代码。

public class FixedThreadPoolDemo {
	public static void main(String[] args) {

		// int nThreads=Runtime.getRuntime().availableProcessors();
		ExecutorService executorService = Executors.newFixedThreadPool(2);

		Runnable saveLogTask = new Runnable() {

			@Override
			public void run() {
				try {
					Thread.currentThread().sleep(2000L);
				 System.out.println("Log is saved by thread"
						+ Thread.currentThread().getId());
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}
		};
		Runnable feedBack = new Runnable() {

			@Override
			public void run() {
				try {
					Thread.currentThread().sleep(2000L);
				   System.out.println("Feedback is called by thread"
						+ Thread.currentThread().getId());
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}
		};

		executorService.submit(saveLogTask);
		System.out.println("Do save log asynchronously.");
		executorService.submit(feedBack);
		System.out.println("Call feedback asynchronously.");

	}
}

其他相关

转载:使用Callable返回结果

分类: JAVA 标签:
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.