---
title: "about ThreadFactory"
author: "headof"
date: "2011-12-28T14:06:56Z"
tags: []
categories: ["编程语言"]
slug: "about-threadfactory"
draft: false
lastmod: "2012-05-23T18:46:23Z"
id: 1328544
url: "https://headof.iteye.com/blog/1328544"
---

ThreadFactory接口，只有一个public方法　newThread。
继承这个接口，可以自己的ThreadFactory，此例为Thread添加一个自己的前缀。
<span style="color:green">
**DaemonThreadFactory **</span>


```java

	/**
	 * 
	 */
	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);

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

```