多线程,高并发初步(六,线程池终极进阶)

常见面试题参考来自:https://blog.csdn.net/u013030086/article/details/84971568
前面5个博客,从最初如何创建线程、到线程的使用、多线程加锁、线程池,一步步到这最后。坚持对我来说。
主要是详细说说:1,ExecutorService接口;2,Executors帮助类;3,ThreadFactory,线程工厂
1,关于ExecutorService,前面已经从源码的角度解释过了。这里之所以拿出来,是前面的内容不够总结性:关于ExecutorService接口,他继承了,包含唯一执行方法的Executor接口,在ExecutorService接口中,定义了很多关于线程执行的状态判断方法。
2,Executors帮助类,我们来分析源码:(冗长而累赘,下面添加注释的都很重要)

public class Executors {
public static ExecutorService newFixedThreadPool(int paramInt) {  // 类型ExecutorService  固定线程池。
    return new ThreadPoolExecutor(paramInt, paramInt, 0L,				// 优点:前面讲过,以下都省略
            TimeUnit.MILLISECONDS, new LinkedBlockingQueue()); // 缺点:在线程池空闲时,即线程池中没有可运行任务时,它不会释放工作线程,还会占用
            //一定的系统资源
}

public static ExecutorService newWorkStealingPool(int paramInt) { // 类型ExecutorService ,需要注意是由ForkJoinPool实现的
    return new ForkJoinPool(paramInt,			
            ForkJoinPool.defaultForkJoinWorkerThreadFactory, null, true);
}

public static ExecutorService newWorkStealingPool() {  
    return new ForkJoinPool(Runtime.getRuntime().availableProcessors(),
            ForkJoinPool.defaultForkJoinWorkerThreadFactory, null, true);
}

public static ExecutorService newFixedThreadPool(int paramInt, // 同上只是多了线程工厂,后面再举例
        ThreadFactory paramThreadFactory) {
    return new ThreadPoolExecutor(paramInt, paramInt, 0L,
            TimeUnit.MILLISECONDS, new LinkedBlockingQueue(),
            paramThreadFactory);
}

public static ExecutorService newSingleThreadExecutor() { // 类型ExecutorService,单一线程池
    return new FinalizableDelegatedExecutorService(new ThreadPoolExecutor( //我们更注重他的优点:它只会用唯一的工作线程来执行任务,保证所有任务
    //按照指定顺序(FIFO, LIFO, 优先级)执行
            1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue()));
}

public static ExecutorService newSingleThreadExecutor( // 同上只是多了线程工厂,后面再举例
        ThreadFactory paramThreadFactory) {
    return new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(
            1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(),
            paramThreadFactory));
}

public static ExecutorService newCachedThreadPool() {  // 类型ExecutorService 
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, // 缺点:一定要注意控制任务的数量,否则,由于大量线程同时运行,很有会造成系统瘫痪
            TimeUnit.SECONDS, new SynchronousQueue()); //前面是说没有上线,其实有的,就是Integer.MAX_VALUE
}

public static ExecutorService newCachedThreadPool(  // 同上只是多了线程工厂,后面再举例
        ThreadFactory paramThreadFactory) {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L,
            TimeUnit.SECONDS, new SynchronousQueue(), paramThreadFactory);
}

public static ScheduledExecutorService newSingleThreadScheduledExecutor() { // 这里需要注意,类型是ScheduledExecutorService 
    return new DelegatedScheduledExecutorService( //这个我们更关注他的优点:支持定时的以及周期性的任务执行,支持定时及周期性任务执行
            new ScheduledThreadPoolExecutor(1));
}

public static ScheduledExecutorService newSingleThreadScheduledExecutor( // 同上只是多了线程工厂,后面再举例
        ThreadFactory paramThreadFactory) {
    return new DelegatedScheduledExecutorService(
            new ScheduledThreadPoolExecutor(1, paramThreadFactory));
}

public static ScheduledExecutorService newScheduledThreadPool(int paramInt) {  //和上面差不多
    return new ScheduledThreadPoolExecutor(paramInt);
}

public static ScheduledExecutorService newScheduledThreadPool(int paramInt,
        ThreadFactory paramThreadFactory) {
    return new ScheduledThreadPoolExecutor(paramInt, paramThreadFactory);
}

public static ExecutorService unconfigurableExecutorService(
        ExecutorService paramExecutorService) {
    if (paramExecutorService == null) {
        throw new NullPointerException();
    }
    return new DelegatedExecutorService(paramExecutorService);
}

public static ScheduledExecutorService unconfigurableScheduledExecutorService(
        ScheduledExecutorService paramScheduledExecutorService) {
    if (paramScheduledExecutorService == null) {
        throw new NullPointerException();
    }
    return new DelegatedScheduledExecutorService(
            paramScheduledExecutorService);
}

public static ThreadFactory defaultThreadFactory() {  // 工厂默认优先级
    return new DefaultThreadFactory();
}

public static ThreadFactory privilegedThreadFactory() { // 线程工厂优先级设置
    return new PrivilegedThreadFactory();
}

public static  Callable callable(Runnable paramRunnable, T paramT) { //以下是Callable
    if (paramRunnable == null) {
        throw new NullPointerException();
    }
    return new RunnableAdapter(paramRunnable, paramT);
}

public static Callable callable(Runnable paramRunnable) {
    if (paramRunnable == null) {
        throw new NullPointerException();
    }
    return new RunnableAdapter(paramRunnable, null);
}

public static Callable callable(
        PrivilegedAction paramPrivilegedAction) {
    if (paramPrivilegedAction == null) {
        throw new NullPointerException();
    }
    new Callable() {
        public Object call() {
            return this.val$action.run();
        }
    };
}

public static Callable callable(
        PrivilegedExceptionAction paramPrivilegedExceptionAction) {
    if (paramPrivilegedExceptionAction == null) {
        throw new NullPointerException();
    }
    new Callable() {
        public Object call() throws Exception {
            return this.val$action.run();
        }
    };
}

public static  Callable privilegedCallable(Callable paramCallable) {
    if (paramCallable == null) {
        throw new NullPointerException();
    }
    return new PrivilegedCallable(paramCallable);
}

public static  Callable privilegedCallableUsingCurrentClassLoader(
        Callable paramCallable) {
    if (paramCallable == null) {
        throw new NullPointerException();
    }
    return new PrivilegedCallableUsingCurrentClassLoader(paramCallable);
}

private Executors() {
}

static final class RunnableAdapter implements Callable {
    final Runnable task;
    final T result;

    RunnableAdapter(Runnable paramRunnable, T paramT) {
        this.task = paramRunnable;
        this.result = paramT;
    }

    public T call() {
        this.task.run();
        return this.result;
    }
}

static final class PrivilegedCallable implements Callable {
    private final Callable task;
    private final AccessControlContext acc;

    PrivilegedCallable(Callable paramCallable) {
        this.task = paramCallable;
        this.acc = AccessController.getContext();
    }

    public T call() throws Exception {
        try {
            AccessController.doPrivileged(new PrivilegedExceptionAction() {
                public T run() throws Exception {
                    return Executors.PrivilegedCallable.this.task.call();
                }
            }, this.acc);
        } catch (PrivilegedActionException localPrivilegedActionException) {
            throw localPrivilegedActionException.getException();
        }
    }
}

static final class PrivilegedCallableUsingCurrentClassLoader implements
        Callable {
    private final Callable task;
    private final AccessControlContext acc;
    private final ClassLoader ccl;

    PrivilegedCallableUsingCurrentClassLoader(Callable paramCallable) {
        SecurityManager localSecurityManager = System.getSecurityManager();
        if (localSecurityManager != null) {
            localSecurityManager
                    .checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);

            localSecurityManager.checkPermission(new RuntimePermission(
                    "setContextClassLoader"));
        }
        this.task = paramCallable;
        this.acc = AccessController.getContext();
        this.ccl = Thread.currentThread().getContextClassLoader();
    }

    public T call() throws Exception {
        try {
            AccessController.doPrivileged(new PrivilegedExceptionAction() {
                public T run() throws Exception {
                    Thread localThread = Thread.currentThread();
                    ClassLoader localClassLoader = localThread
                            .getContextClassLoader();
                    if (Executors.PrivilegedCallableUsingCurrentClassLoader.this.ccl == localClassLoader) {
                        return Executors.PrivilegedCallableUsingCurrentClassLoader.this.task
                                .call();
                    }
                    localThread
                            .setContextClassLoader(Executors.PrivilegedCallableUsingCurrentClassLoader.this.ccl);
                    try {
                        return Executors.PrivilegedCallableUsingCurrentClassLoader.this.task
                                .call();
                    } finally {
                        localThread.setContextClassLoader(localClassLoader);
                    }
                }
            }, this.acc);
        } catch (PrivilegedActionException localPrivilegedActionException) {
            throw localPrivilegedActionException.getException();
        }
    }
}

static class DefaultThreadFactory implements ThreadFactory {
    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    DefaultThreadFactory() {
        SecurityManager localSecurityManager = System.getSecurityManager();

        this.group = (localSecurityManager != null ? localSecurityManager
                .getThreadGroup() : Thread.currentThread().getThreadGroup());

        this.namePrefix = ("pool-" + poolNumber.getAndIncrement() + "-thread-");
    }

    public Thread newThread(Runnable paramRunnable) {
        Thread localThread = new Thread(this.group, paramRunnable,
                this.namePrefix + this.threadNumber.getAndIncrement(), 0L);
        if (localThread.isDaemon()) {
            localThread.setDaemon(false);
        }
        if (localThread.getPriority() != 5) {
            localThread.setPriority(5);
        }
        return localThread;
    }
}

static class PrivilegedThreadFactory extends Executors.DefaultThreadFactory {
    private final AccessControlContext acc;
    private final ClassLoader ccl;

    PrivilegedThreadFactory() {
        SecurityManager localSecurityManager = System.getSecurityManager();
        if (localSecurityManager != null) {
            localSecurityManager
                    .checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);

            localSecurityManager.checkPermission(new RuntimePermission(
                    "setContextClassLoader"));
        }
        this.acc = AccessController.getContext();
        this.ccl = Thread.currentThread().getContextClassLoader();
    }

    public Thread newThread(final Runnable paramRunnable)
{
  super.newThread(new Runnable()
  {
    public void run()
    {
      AccessController.doPrivileged(new PrivilegedAction()
      {
        public Void run()
        {
          Thread.currentThread().setContextClassLoader(Executors.PrivilegedThreadFactory.this.ccl);
          Executors.PrivilegedThreadFactory.1.this.val$r.run();
          return null;
        }
      }, Executors.PrivilegedThreadFactory.this.acc);
    }
  });
}
}

static class DelegatedExecutorService extends AbstractExecutorService {
    private final ExecutorService e;

    DelegatedExecutorService(ExecutorService paramExecutorService) {
        this.e = paramExecutorService;
    }

    public void execute(Runnable paramRunnable) {
        this.e.execute(paramRunnable);
    }

    public void shutdown() {
        this.e.shutdown();
    }

    public List shutdownNow() {
        return this.e.shutdownNow();
    }

    public boolean isShutdown() {
        return this.e.isShutdown();
    }

    public boolean isTerminated() {
        return this.e.isTerminated();
    }

    public boolean awaitTermination(long paramLong, TimeUnit paramTimeUnit)
            throws InterruptedException {
        return this.e.awaitTermination(paramLong, paramTimeUnit);
    }

    public Future submit(Runnable paramRunnable) { // Future
        return this.e.submit(paramRunnable);
    }

    public  Future submit(Callable paramCallable) {
        return this.e.submit(paramCallable);
    }

    public  Future submit(Runnable paramRunnable, T paramT) {
        return this.e.submit(paramRunnable, paramT);
    }

    public  List> invokeAll(
            Collection> paramCollection)
            throws InterruptedException {
        return this.e.invokeAll(paramCollection);
    }

    public  List> invokeAll(
            Collection> paramCollection,
            long paramLong, TimeUnit paramTimeUnit)
            throws InterruptedException {
        return this.e.invokeAll(paramCollection, paramLong, paramTimeUnit);
    }

    public  T invokeAny(Collection> paramCollection)
            throws InterruptedException, ExecutionException {
        return this.e.invokeAny(paramCollection);
    }

    public  T invokeAny(
            Collection> paramCollection,
            long paramLong, TimeUnit paramTimeUnit)
            throws InterruptedException, ExecutionException,
            TimeoutException {
        return this.e.invokeAny(paramCollection, paramLong, paramTimeUnit);
    }
}

static class FinalizableDelegatedExecutorService extends
        Executors.DelegatedExecutorService {
    FinalizableDelegatedExecutorService(ExecutorService paramExecutorService) {
        super();
    }

    protected void finalize() {
        super.shutdown();
    }
}

static class DelegatedScheduledExecutorService extends
        Executors.DelegatedExecutorService implements
        ScheduledExecutorService {
    private final ScheduledExecutorService e;

    DelegatedScheduledExecutorService(
            ScheduledExecutorService paramScheduledExecutorService) {
        super();
        this.e = paramScheduledExecutorService;
    }

    public ScheduledFuture schedule(Runnable paramRunnable,
            long paramLong, TimeUnit paramTimeUnit) {
        return this.e.schedule(paramRunnable, paramLong, paramTimeUnit);
    }

    public  ScheduledFuture schedule(Callable paramCallable,
            long paramLong, TimeUnit paramTimeUnit) {
        return this.e.schedule(paramCallable, paramLong, paramTimeUnit);
    }

    public ScheduledFuture scheduleAtFixedRate(Runnable paramRunnable,
            long paramLong1, long paramLong2, TimeUnit paramTimeUnit) {
        return this.e.scheduleAtFixedRate(paramRunnable, paramLong1,
                paramLong2, paramTimeUnit);
    }

    public ScheduledFuture scheduleWithFixedDelay(
            Runnable paramRunnable, long paramLong1, long paramLong2,
            TimeUnit paramTimeUnit) {
        return this.e.scheduleWithFixedDelay(paramRunnable, paramLong1,
                paramLong2, paramTimeUnit);
    }
}
}
 
  

3,ThreadFactory(接口)线程工厂(这里我们只举1个例子)

package test;

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


class Task implements Runnable { // 这里闹了个乌龙,我在同一个包下建了相同类名,自己还疑惑了半天。ばっが

int cString;
public Task(int ID) {
    this.cString = ID;
}
@Override
public void run() {
    System.out.println(Thread.currentThread().getName() + ":" + cString);
}
}

// 不适用内部内实现
//class DaemonThreadFactory implements ThreadFactory {
//    @Override
//    public Thread newThread(Runnable r) {
//        Thread thread=new Thread(r);
//        thread.setDaemon(true);
//        return thread;
//    }
//}

public class TestThreadFactory {

public static void main(String[] args) {

    // 这里采用内部内实现
    ThreadFactory threadFactory = new ThreadFactory() {

        @Override
        public Thread newThread(Runnable r) {
           Thread thread = new Thread(r);
           thread.setDaemon(true); // 设置为保护线程,默认为一般线程
            return thread;
        }
    };

    ExecutorService service = Executors.newFixedThreadPool(4, threadFactory);
    // 不使用内部内方式
    // ExecutorService service = Executors.newFixedThreadPool(4, new DaemonThreadFactory());
    for(int i = 0; i < 4; i++) {
        service.submit(new Task(i));
    }
    service.shutdown();
}
}

后记:虽然看着是写完了,但是实际的应用确是很复杂的。其次每个人都在努力,不要骄傲,不要自满。踏踏实实,走好自己的路。
望能看到这里的人,万事如意,脱离单身狗??。

你可能感兴趣的:(多线程)