0
点赞
收藏
分享

微信扫一扫

ThreadPoolExecutor 例子

人间四月天i 2022-03-11 阅读 27

1. 重写RejectedExecutionHandler

线程池在BlockingQueue用完的情况下,会执行这里。可以利用这个方法把数据存下来。等空闲的时候在运行。

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
public class UserRejectHandler implements RejectedExecutionHandler {
    @Override
    public void rejectedExecution(Runnable runnable, ThreadPoolExecutor threadPoolExecutor) {
        System.out.println("task rejected. " + threadPoolExecutor.toString());
    }
}


2. 创建ThreadFactory 。生产Thread

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
// UserThreadFactory.java
public class UserThreadFactory implements ThreadFactory {
    private final String namePrefix;
    private final AtomicInteger nextId = new AtomicInteger(1);
    UserThreadFactory(String whatFeatureOfGroup) {
        this.namePrefix = "UserThreadFactory's " + whatFeatureOfGroup + "-Worker-";
    }

    public Thread newThread(Runnable runnable) {
        String name = this.namePrefix + nextId.getAndIncrement();
        Thread thread = new Thread(null, runnable, name, 0);
        System.out.println(thread.getName());
        return thread;
    }
}
class Task implements Runnable {
    private final AtomicLong count = new AtomicLong(0L);
    public void run() {
        System.out.println("Starting to run running_" + count.getAndIncrement());
        try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
        System.out.println("End to run running_" + count.getAndIncrement());
    }
}


3. 执行15个任务。

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class UserThreadPool {
    public static void main(String[] args) {
        BlockingDeque<Runnable> blockingDeque = new LinkedBlockingDeque<>(13);
        UserThreadFactory f1 = new UserThreadFactory("UserThreadFactory 1");
        UserRejectHandler handler = new UserRejectHandler();
        ThreadPoolExecutor threadPoolFirst = new ThreadPoolExecutor(1, 2,
                60, TimeUnit.SECONDS, blockingDeque, f1, handler);
        Runnable task = new Task();
        for (int i = 0; i < 15; i++) {
            threadPoolFirst.execute(task);
            System.out.println("threadPoolFirst.execute.."+i);
        }   
    }
}

执行结果

举报

相关推荐

0 条评论