All Downloads are FREE. Search and download functionalities are using the official Maven repository.

mtons.spider.SpiderExecutor Maven / Gradle / Ivy

package mtons.spider;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 任务执行器
 * Created by langhsu on 2015/11/3.
 */
public class SpiderExecutor {

    private ExecutorService executorService;

    private int threads;

    private AtomicInteger threadAlive = new AtomicInteger();

    private ReentrantLock reentrantLock = new ReentrantLock();

    private Condition condition = reentrantLock.newCondition();

    public SpiderExecutor(int threads) {
        this.threads = threads;
        this.executorService = Executors.newFixedThreadPool(threads);
    }

    public SpiderExecutor(int threads, ExecutorService executorService) {
        this.threads = threads;
        this.executorService = executorService;
    }

    public int getThreadAlive() {
        return threadAlive.get();
    }

    public void execute(final Runnable runnable) {

        if (threadAlive.get() >= threads) {
            try {
                reentrantLock.lock();
                while (threadAlive.get() >= threads) {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                    }
                }
            } finally {
                reentrantLock.unlock();
            }
        }
        threadAlive.incrementAndGet();

        executorService.execute(() -> {
            try {
                runnable.run();
            } finally {
                try {
                    reentrantLock.lock();
                    threadAlive.decrementAndGet();
                    condition.signal();
                } finally {
                    reentrantLock.unlock();
                }
            }
        });
    }

    public boolean isShutdown() {
        return executorService.isShutdown();
    }

    public void shutdown() {
        executorService.shutdown();
    }

    public boolean awaitTermination(int seconds) throws InterruptedException {
        return executorService.awaitTermination(seconds, TimeUnit.SECONDS);
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy