ThreadPoolExecutor中的SynchronousQueue

Una*_*ahD 3 java multithreading blockingqueue threadpool threadpoolexecutor

我试图了解队列中的行为ThreadPoolExecutor.在下面的程序中,当我使用时LinkedBlockingQueue,我一次只能向线程池提交一个任务.但是,如果我取代LinkedBlockingQueueSynchronousQueue,我可以在瞬间提交所有5个任务到池中.如何SynchronousQueue不同于LinkedBlockingQueue在这种情况下?

Java程序:

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Sample {
    public static void main(String[] args) throws InterruptedException {
        LinkedBlockingQueue<Runnable> threadPoolQueue = new LinkedBlockingQueue<>();
//      SynchronousQueue<Runnable> threadPoolQueue = new SynchronousQueue<>();
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        ThreadPoolExecutor tpe = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, threadPoolQueue, threadFactory);
        Runnable np;

        for (int i = 1; i <= 5; i++) {
            np = new SampleWorker("ThreadPoolWorker " + i);
            tpe.submit(np);
        }

        System.out.println(tpe.getCorePoolSize());
        System.out.println(tpe.getPoolSize());
        System.out.println(tpe.getActiveCount());

        tpe.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
        tpe.shutdown();
        System.out.println("Main task finished");
    }
}

class SampleWorker implements Runnable {
    private String workerName;

    SampleWorker(String tName) {
        workerName = tName;
    }

    @Override
    public void run() {
        try {
            for (int i = 1; i <= 10; i++) {
                Thread.sleep(3000);
                System.out.println(this.workerName);
            }
            System.out.println(this.workerName + " finished");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

孙兴斌*_*孙兴斌 7

当您提交任务时ThreadPoolExecutor,它的工作方式如下:

if (numberOfWorkingThreads < corePoolSize) {
   startNewThreadAndRunTask();
} else if (workQueue.offer(task)) {
   if (numberOfWorkingThreads == 0) {
       startNewThreadAndRunTask();
   }
} else if (numberOfWorkingThreads < maxPoolSize)
    startNewThreadAndRunTask();
} else {
    rejectTask();
}
Run Code Online (Sandbox Code Playgroud)
  • 当使用LinkedBlockingQueue没有初始值时, workQueue.offer(task)将始终成功,导致只启动一个线程.
  • 在调用时SynchronousQueue.offer(task),只有当另一个线程正在等待接收它时才会成功.由于没有等待线程,false因此每次都会返回并创建新线程.