第0章:簡介
第1節:參考網站/文檔
http://lavasoft.blog.51cto.com/62575/27069/
http://programming.iteye.com/blog/158568
http://www.cnblogs.com/rollenholt/archive/2011/08/28/2156357.html
http://www.cnblogs.com/jackyuj/archive/2010/11/24/1886553.html
javaJDK文檔
java併發編程實踐 (電子工業出版社 方妙譯)
第2節:札記
第1章:實例
第1節:線程服務工具類
(1)線程池工具類 ExecutorServiceUtils.java
package com.mcc.core.concurrent;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 線程服務工具類
*
* @author <a href="mailto:[email protected]">menergy</a>
* DateTime: 13-12-26 下午6:05
*/
public abstract class ExecutorServiceUtils {
// 線程池
private static Map<String, ExecutorService> executorMap = new ConcurrentHashMap<String, ExecutorService>();
/**
* 線程池緩存
*
* @param name 線程池名稱
* @param size 線程池大小
* @return 線程池
*/
public static ExecutorService getExecutor(final String name, int size) {
if (!executorMap.containsKey(name)) {
size = size > 0 ? size : 1;
BasicThreadFactory factory = new BasicThreadFactory.Builder()
.namingPattern(name + "-thread-%d")
.priority(Thread.MAX_PRIORITY)
.build();
executorMap.put(name, Executors.newFixedThreadPool(size, factory));
}
return executorMap.get(name);
}
public static void main(String args[]){
Executor executor = ExecutorServiceUtils.getExecutor("test",3);
executor.execute(new Runnable(){
@Override
public void run() {
for(int i = 0; i < 10; i++){
try {
System.out.println("thread1 running -- " + i);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
executor.execute(new Runnable(){
@Override
public void run() {
for(int i = 0; i < 10; i++){
try {
System.out.println("thread2 running -- " + i);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
executor.execute(new Runnable(){
@Override
public void run() {
for(int i = 0; i < 10; i++){
try {
System.out.println("thread3 running -- " + i);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
}
(2)線程工廠基類BasicThreadFactory.java
package com.mcc.core.concurrent;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;
/**
* 線程工廠基類
*
* @author <a href="mailto:[email protected]">menergy</a>
* DateTime: 13-12-26 下午5:50
*/
public class BasicThreadFactory implements ThreadFactory {
//計算線程工廠創建的線程數
private final AtomicLong threadCounter;
//包裝工廠
private final ThreadFactory wrappedFactory;
//非捕獲異常處理
private final Thread.UncaughtExceptionHandler uncaughtExceptionHandler;
//線程命名模式
private final String namingPattern;
//優先級
private final Integer priority;
//後臺狀態標識
private final Boolean daemonFlag;
/**
* Creates a new instance of {@code ThreadFactoryImpl} and configures it
* from the specified {@code Builder} object.
*
* @param builder the {@code Builder} object
*/
private BasicThreadFactory(Builder builder) {
if (builder.wrappedFactory == null) {
wrappedFactory = Executors.defaultThreadFactory();
} else {
wrappedFactory = builder.wrappedFactory;
}
namingPattern = builder.namingPattern;
priority = builder.priority;
daemonFlag = builder.daemonFlag;
uncaughtExceptionHandler = builder.exceptionHandler;
threadCounter = new AtomicLong();
}
/**
* 獲取包裝工廠
* @return 不會返回null
*/
public final ThreadFactory getWrappedFactory() {
return wrappedFactory;
}
/**
* 獲取命名模式
* @return
*/
public final String getNamingPattern() {
return namingPattern;
}
/**
* 獲取是否爲後臺線程標識
* @return
*/
public final Boolean getDaemonFlag() {
return daemonFlag;
}
/**
* 獲取優先級
* @return
*/
public final Integer getPriority() {
return priority;
}
/**
* 獲取非捕獲異常處理器
* @return
*/
public final Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() {
return uncaughtExceptionHandler;
}
/**
* 獲取創建的線程數量
* @return
*/
public long getThreadCount() {
return threadCounter.get();
}
/**
* 創建新線程
* @param r
* @return
*/
public Thread newThread(Runnable r) {
Thread t = getWrappedFactory().newThread(r);
initializeThread(t);
return t;
}
/**
* 初始化線程
* @param t
*/
private void initializeThread(Thread t) {
if (getNamingPattern() != null) {
Long count = Long.valueOf(threadCounter.incrementAndGet());
t.setName(String.format(getNamingPattern(), count));
}
if (getUncaughtExceptionHandler() != null) {
t.setUncaughtExceptionHandler(getUncaughtExceptionHandler());
}
if (getPriority() != null) {
t.setPriority(getPriority().intValue());
}
if (getDaemonFlag() != null) {
t.setDaemon(getDaemonFlag().booleanValue());
}
}
/**
* 創建器類
*/
public static class Builder
implements com.mcc.core.concurrent.Builder<BasicThreadFactory> {
//包裝工廠
private ThreadFactory wrappedFactory;
//非捕獲異常處理器
private Thread.UncaughtExceptionHandler exceptionHandler;
//命名模式
private String namingPattern;
//優先級
private Integer priority;
//後臺標識
private Boolean daemonFlag;
/**
* 創建包裝工廠
* @param factory
* @return
*/
public Builder wrappedFactory(ThreadFactory factory) {
if (factory == null) {
throw new NullPointerException(
"Wrapped ThreadFactory must not be null!");
}
wrappedFactory = factory;
return this;
}
/**
* 設置命名模式
* @param pattern
* @return
*/
public Builder namingPattern(String pattern) {
if (pattern == null) {
throw new NullPointerException(
"Naming pattern must not be null!");
}
namingPattern = pattern;
return this;
}
/**
* 設置後臺標識
* @param f
* @return
*/
public Builder daemon(boolean f) {
daemonFlag = Boolean.valueOf(f);
return this;
}
/**
* 設置優先級
* @param prio
* @return
*/
public Builder priority(int prio) {
priority = Integer.valueOf(prio);
return this;
}
/**
* 設置非捕獲異常處理器
* @param handler
* @return
*/
public Builder uncaughtExceptionHandler(
Thread.UncaughtExceptionHandler handler) {
if (handler == null) {
throw new NullPointerException(
"Uncaught exception handler must not be null!");
}
exceptionHandler = handler;
return this;
}
/**
* 重置構建參數
*/
public void reset() {
wrappedFactory = null;
exceptionHandler = null;
namingPattern = null;
priority = null;
daemonFlag = null;
}
/**
* 構建基類線程工廠
* @return
*/
public BasicThreadFactory build() {
BasicThreadFactory factory = new BasicThreadFactory(this);
reset();
return factory;
}
}
}
(3)構建器接口Builder.java
package com.mcc.core.concurrent;
/**
* 構建器接口
*
* @author <a href="mailto:[email protected]">menergy</a>
* DateTime: 13-12-26 下午5:56
*/
public interface Builder<T> {
public T build();
}
第2節:自定義線程創建器
package com.mcc.core.concurrent;
import com.mcc.core.reflection.ClassUtils;
import java.io.Serializable;
/**
*自定義線程創建器
* @author <a href="mailto:[email protected]">menergy</a>
* @version 2013-12-8
*/
public class CustomizableThreadCreator implements Serializable {
private static final long serialVersionUID = -8401919277161997988L;
private String threadNamePrefix;
private int threadPriority = Thread.NORM_PRIORITY;
private boolean daemon = false;
private ThreadGroup threadGroup;
private int threadCount = 0;
private final Object threadCountMonitor = new SerializableMonitor();
public CustomizableThreadCreator() {
this.threadNamePrefix = getDefaultThreadNamePrefix();
}
public CustomizableThreadCreator(String threadNamePrefix) {
this.threadNamePrefix = (threadNamePrefix != null ? threadNamePrefix : getDefaultThreadNamePrefix());
}
/**
* 設置線程名前綴
*
* @param threadNamePrefix
*/
public void setThreadNamePrefix(String threadNamePrefix) {
this.threadNamePrefix = (threadNamePrefix != null ? threadNamePrefix : getDefaultThreadNamePrefix());
}
/**
* 獲取線程名前綴
*
* @return
*/
public String getThreadNamePrefix() {
return this.threadNamePrefix;
}
/**
* 設置線程優先級
*
* @param threadPriority
*/
public void setThreadPriority(int threadPriority) {
this.threadPriority = threadPriority;
}
/**
* 獲取線程優先級
*
* @return
*/
public int getThreadPriority() {
return this.threadPriority;
}
/**
* 設置是否是後臺線程
*
* @param daemon
*/
public void setDaemon(boolean daemon) {
this.daemon = daemon;
}
/**
* 判斷是否是後臺線程
*
* @return
*/
public boolean isDaemon() {
return this.daemon;
}
/**
* 設置線程組名
*
* @param name
*/
public void setThreadGroupName(String name) {
this.threadGroup = new ThreadGroup(name);
}
/**
* 設置線程組名
*
* @param threadGroup
*/
public void setThreadGroup(ThreadGroup threadGroup) {
this.threadGroup = threadGroup;
}
/**
* 獲取線程組
*
* @return
*/
public ThreadGroup getThreadGroup() {
return this.threadGroup;
}
/**
* 創建線程
*
* @param runnable
* @return
*/
public Thread createThread(Runnable runnable) {
Thread thread = new Thread(getThreadGroup(), runnable, nextThreadName());
thread.setPriority(getThreadPriority());
thread.setDaemon(isDaemon());
return thread;
}
/**
* 下一個線程名
*
* @return
*/
protected String nextThreadName() {
int threadNumber = 0;
synchronized (this.threadCountMonitor) {
this.threadCount++;
threadNumber = this.threadCount;
}
return getThreadNamePrefix() + threadNumber;
}
/**
* 獲取默認線程名前綴
*
* @return
*/
protected String getDefaultThreadNamePrefix() {
return ClassUtils.getShortClassName(getClass()) + "-";
}
/**
* 空對象作爲序列化監控對象
*
* @author <a href="mailto:[email protected]">menergy</a>
* @version 2013-12-8
*/
private static class SerializableMonitor implements Serializable {
}
/**
*
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}