ExecutorService使用

参考: http://www.jz123.cn/text/0821440.html

package com.pure;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class TestThreadPool {
	public static void main(String args[]) throws InterruptedException {
		ExecutorService exec = Executors.newFixedThreadPool(10, new MyThreadFactoy());
		for (int index = 0; index < 10; index++) {
			Runnable run = new Runnable() {
				public void run() {
					long time = (long) (Math.random() * 1000);
					System.out.println("Sleeping " + time + "ms" + "/" + Thread.currentThread().getName());

					try {
						Thread.sleep(time);
					} catch (InterruptedException e) {
					}
				}
			};
			exec.execute(run);
		}
		// must shutdown
		exec.shutdown();
	}
}

class MyThreadFactoy implements ThreadFactory {
	@Override
	public Thread newThread(Runnable r) {
		Thread t = new Thread(r);
		return t;
	}

}



主要就是这个类的几个方法。

类 Executors

  此类中提供的一些方法有:

  1.1 public static ExecutorService newCachedThreadPool()

  创建一个可根据需要创建新线程的线程池,但是在以前构造的线程可用时将重用它们。对于执行很多短期异步任务的程序而言,这些线程池通常可提高程序性能。

  1.2 public static ExecutorService newFixedThreadPool(int nThreads)

  创建一个可重用固定线程数的线程池,以共享的无界队列方式来运行这些线程。

  1.3 public static ExecutorService newSingleThreadExecutor()

  创建一个使用单个 worker 线程的 Executor,以无界队列方式来运行该线程。

  这三个方法都可以配合接口ThreadFactory的实例一起使用。并且返回一个ExecutorService接口的实例。

你可能感兴趣的:(java,thread,html)