线程池模版

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadPoolTest {
     

    private static final Logger logger = LoggerFactory.getLogger(ThreadPoolTest.class);

    private static int corePoolSize = 4;
    private static int maximumPoolSize = 8;
    private static long keepAliveTime = 5;

    private static final ExecutorService service = new ThreadPoolExecutor(corePoolSize,
            maximumPoolSize, keepAliveTime, TimeUnit.MINUTES, new LinkedBlockingQueue<>(),
            new MyFactory("work-"), new MyRejectedExecutionHandler());


    static class Work implements Runnable {
     

        @Override
        public void run() {
     
            // 业务逻辑
            logger.info("The task is being executed ...");
        }
    }

    static class MyFactory implements ThreadFactory {
     

        private final String namePrefix;
        private final AtomicInteger nextId = new AtomicInteger(1);

        public MyFactory(String namePrefix) {
     
            this.namePrefix = namePrefix;
        }

        @Override
        public Thread newThread(Runnable target) {
     
            String name = namePrefix + nextId.getAndIncrement();
            return new Thread(target, name);
        }
    }

    static class MyRejectedExecutionHandler implements RejectedExecutionHandler {
     
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
     
            logger.warn("MyRejectedExecutionHandler.rejectedExecution reject");
        }
    }

    public static void main(String[] args) {
     
        for (int i = 0; i < 100; i++) {
     
            service.submit(new Work());
        }
    }
}

你可能感兴趣的:(java)