java多线程(1):基础

第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

    }

}








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章