ArrayBlockingQueue and ExecutorService
package test;import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;public class Test { public static void main(String[] args) { //executorServiceTest() arrayBlockingQueueTest(); } public static void arrayBlockingQueueTest(){ BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(5); ThreadPoolExecutor executor=new ThreadPoolExecutor(3, Runtime.getRuntime().availableProcessors(), 1, TimeUnit.HOURS, queue,new ThreadPoolExecutor.CallerRunsPolicy()); for(int i=0;i<100;i++){ final int index=i; System.out.println("task:"+(i+1)); Runnable run=new Runnable() { @Override public void run() { System.out.println("thread start" + index); try { Thread.sleep(1000*3); }catch(Exception e){ e.printStackTrace(); } System.out.println("thread end "+index); } }; executor.execute(run); } } public static void executorServiceTest(){ ExecutorService service = Executors.newFixedThreadPool(2); for(int i=0;i<100;i++){ final int index=i; System.out.println("task:"+(i+1)); Runnable run=new Runnable() { @Override public void run() { System.out.println("thread start" + index); try { Thread.sleep(1000*3); }catch(Exception e){ e.printStackTrace(); } System.out.println("thread end "+index); } }; service.execute(run); } }}
Result of calling the executorServiceTest Method
task:1task:2task:3thread start0task:4task:5thread start1task:6task:7task:8task:9task:10thread end 0thread start2thread end 1thread start3thread end 2thread end 3thread start4thread start5thread end 5thread start6thread end 4thread start7thread end 6thread end 7thread start8thread start9thread end 8thread end 9
Call arrayBlockingQueueTest to run the result
task:1task:2task:3thread start0thread start1task:4thread start2task:5task:6task:7thread start6thread end 1thread end 6thread end 0thread end 2thread start5thread start4task:8task:9thread start3task:10thread end 5thread end 3thread end 4thread start9thread start8thread start7thread end 9thread end 8thread end 7
From the running results, it is not difficult to see that ExecutorService is used to call all threads and put them in the memory.
In ArrayBlockingQueue, there is a thread capacity, and there are four in the running results, which achieves the effect of automatic blocking of queues.