ExecutorService
作者:互联网
package com.demo.test;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Date;
import java.util.concurrent.*;
@SpringBootTest
public class CompletionServiceTest {
@Test
public void test() throws ExecutionException, InterruptedException {
//future.get() 阻塞 date相同
// ExecutorService executorService = Executors.newFixedThreadPool(10);
// for (int i = 0; i < 5; i++) {
// Future future = executorService.submit(new CallableTest(new SendTest()));
// Future future2 = executorService.submit(new CallableTest2(new SendTest()));
// System.out.println(""+future.get()+new Date());
// System.out.println(""+future2.get()+new Date());
// }
//使用CompletionService不会阻塞
ExecutorService executorService = Executors.newFixedThreadPool(10);
CompletionService completionService = new ExecutorCompletionService(executorService);
for (int i = 0; i < 5; i++) {
completionService.submit(new CallableTest(new SendTest()));
completionService.submit(new CallableTest2(new SendTest()));
//completionService.take()也是阻塞,如果只有两个任务,第三个take阻塞,poll不会阻塞
System.out.println("" + completionService.take().get() + new Date());
System.out.println("" + completionService.take().get() + new Date());
// System.out.println("" + completionService.take().get() + new Date());
}
}
}
class CallableTest implements Callable {
SendTest sendTest;
CallableTest(SendTest sendTest) {
this.sendTest = sendTest;
}
@Override
public Object call() throws Exception {
Thread.sleep(5000);
sendTest.send();
return "11111" + ":" + Thread.currentThread();
}
}
class CallableTest2 implements Callable {
SendTest sendTest;
CallableTest2(SendTest sendTest) {
this.sendTest = sendTest;
}
@Override
public Object call() throws Exception {
Thread.sleep(2000);
sendTest.send();
return "22222" + ":" + Thread.currentThread();
}
}
class SendTest {
public void send() {
// System.out.println("send"+new Date()+":"+Thread.currentThread());
}
}
标签:completionService,System,Date,new,sendTest,ExecutorService,SendTest 来源: https://www.cnblogs.com/ococo/p/16696290.html