ITeye博客

about ThreadFactory

headof · 2011-12-28 14:06 · java · 编程语言 · Markdown

ThreadFactory接口,只有一个public方法 newThread。 继承这个接口,可以自己的ThreadFactory,此例为Thread添加一个自己的前缀。 **DaemonThreadFactory **


	/**
	 * 
	 */
	public class DaemonThreadFactory implements ThreadFactory {
		//
		private String prefix;
		private volatile int threadId;
		
		/**
		 * 
		 * @param prefix
		 */
		public DaemonThreadFactory(String prefix) {
			this.prefix = prefix;
		}

		/**
		 * 
		 */
		public Thread newThread(Runnable runnable) {
			Thread r = new Thread(runnable);
			r.setName(prefix + (threadId++));
			r.setDaemon(true);
			return r;
		}
	}

接合Executors使用. 例如.Executors.newSingleThreadExecutor(ThreadFactory threadFactory);


		ExecutorService executor = Executors.newSingleThreadExecutor(new DaemonThreadFactory());
		executor.submit(new Runnable() {
			public void run() {
				try {
					//do some thing
				} catch (Throwable e) {
				}
			}
		});

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。