本文整理汇总了Java中java.util.concurrent.ExecutorService.shutdown方法的典型用法代码示例。如果您正苦于以下问题:Java ExecutorService.shutdown方法的具体用法?Java ExecutorService.shutdown怎么用?Java ExecutorService.shutdown使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.util.concurrent.ExecutorService
的用法示例。
在下文中一共展示了ExecutorService.shutdown方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: main
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
public static void main(String[] args) throws Exception
{
// All must share a single CountDownLatch object:
CountDownLatch latch = new CountDownLatch(5);
ExecutorService exec = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++)
{
exec.execute(new Entrance3(latch, i));
}
TimeUnit.SECONDS.sleep(3);
Entrance3.cancel();
exec.shutdown();
latch.await(); // Wait for results
System.out.println("Total: " + Entrance3.getTotalCount());
System.out.println("Sum of Entrances: " + Entrance3.sumEntrances());
}
示例2: testDubboMultiThreadInvoke
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
public void testDubboMultiThreadInvoke() throws Exception
{
Exporter<?> rpcExporter = protocol.export(proxy.getInvoker(new DemoServiceImpl(), DemoService.class, URL.valueOf("dubbo://127.0.0.1:20259/TestService")));
final AtomicInteger counter = new AtomicInteger();
final DemoService service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:20259/TestService")));
assertEquals(service.getSize(new String[]{"123", "456", "789"}), 3);
final StringBuffer sb = new StringBuffer();
for(int i=0;i<1024*64+32;i++)
sb.append('A');
assertEquals(sb.toString(), service.echo(sb.toString()));
ExecutorService exec = Executors.newFixedThreadPool(10);
for(int i=0;i<10;i++)
{
final int fi = i;
exec.execute(new Runnable(){
public void run()
{
for(int i=0;i<30;i++)
{
System.out.println(fi+":"+counter.getAndIncrement());
assertEquals(service.echo(sb.toString()), sb.toString());
}
}
});
}
exec.shutdown();
exec.awaitTermination(10, TimeUnit.SECONDS);
rpcExporter.unexport();
}
示例3: process
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
public final void process(final ArrayList<Object> arraylist, final int threadPoolSize) {
final ExecutorService executor = Executors.newFixedThreadPool(threadPoolSize);
if(arraylist.size() >= threadPoolSize && arraylist.size() >= MINARRAYLISTSIZE) {
final int steps = arraylist.size() / threadPoolSize;
for(int i = 0; i < threadPoolSize; i++) {
final int u = i;
Runnable run = new Runnable() {
@Override
public void run() {
final int extra = ((u == threadPoolSize - 1) ? (steps * threadPoolSize) - arraylist.size() : 0);
for(int z = 0; z < steps + extra; z++) {
final int pos = (u * steps + z);
arraylist.set(pos, process(arraylist.get(pos)));
}
}
};
executor.execute(run);
}
executor.shutdown();
try {
executor.awaitTermination(1, TimeUnit.DAYS);
} catch (Exception ex) {
}
} else {
for(int i = 0; i < arraylist.size(); i++) {
arraylist.set(i, process(arraylist.get(i)));
}
}
}
示例4: waitForTask
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
private void waitForTask() throws Exception {
if (!DirectByteBufferPool.initInstance(config.getByteBufferSize(), Config.getMaxTakePollIter())) {
// this is really wrong ... It cannot be already initialized
throw new FDTProcolException("The buffer pool cannot be already initialized");
}
ExecutorService executor = null;
ServerSocketChannel ssc = null;
ServerSocket ss = null;
Selector sel = null;
try {
executor = Utils.getStandardExecService("[ Acceptable ServersThreadPool ] ",
2,
10,
new ArrayBlockingQueue<Runnable>(65500),
Thread.NORM_PRIORITY - 2);
ssc = ServerSocketChannel.open();
ssc.configureBlocking(false);
ss = ssc.socket();
ss.bind(new InetSocketAddress(config.getPort()));
sel = Selector.open();
ssc.register(sel, SelectionKey.OP_ACCEPT);
System.out.println("READY");
Utils.waitAndWork(executor, ss, sel, config);
} finally {
logger.log(Level.INFO, "[FDT] [ waitForTask ] main loop FINISHED!");
// close all the stuff
Utils.closeIgnoringExceptions(ssc);
Utils.closeIgnoringExceptions(sel);
Utils.closeIgnoringExceptions(ss);
if (executor != null) {
executor.shutdown();
}
}
}
示例5: shutdownExecutor
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
public static void shutdownExecutor(ExecutorService executor) {
executor.shutdown();
try {
executor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
if (! executor.isTerminated()) {
Logger.logShutdownMessage("some threads didn't terminate, forcing shutdown");
executor.shutdownNow();
}
}
示例6: main
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
public static void main(String[] args){
//ExecutorService 的生命周期包括三种状态:运行、关闭、终止。创建后便进入运行状态,当调用了 shutdown()方法时
// ,便进入关闭状态,此时意味着 ExecutorService 不再接受新的任务,但它还在执行已经提交了的任务
ExecutorService executorService = Executors.newCachedThreadPool();
// ExecutorService executorService = Executors.newFixedThreadPool(5);
//创建一个单线程化的Executor。
// ExecutorService executorService = Executors.newSingleThreadExecutor();
for (int i = 0; i < 5; i++){
executorService.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "线程被调用了。");
}
});
System.out.println("************* a" + i + " *************");
}
executorService.shutdown();
}
示例7: getList
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
/** 根据Id查询(cls返回类型Class) */
public <K> List<K> getList(List<Long> ids, Class<K> cls) {
List<K> list = InstanceUtil.newArrayList();
if (ids != null) {
for (int i = 0; i < ids.size(); i++) {
list.add(null);
}
ExecutorService executorService = Executors.newFixedThreadPool(10);
for (int i = 0; i < ids.size(); i++) {
final int index = i;
executorService.execute(new Runnable() {
public void run() {
T t = queryById(ids.get(index));
K k = InstanceUtil.to(t, cls);
list.set(index, k);
}
});
}
executorService.shutdown();
try {
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
} catch (InterruptedException e) {
logger.error("awaitTermination", "", e);
}
}
return list;
}
示例8: run
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
/**
* Runs the command.
*
* @param command the list of command line tokens
* @return the output of the command as a list of lines
* @throws GradleException if the command exited with non-zero exit code
*/
public List<String> run(List<String> command) throws IOException, InterruptedException {
if (logger != null) {
logger.debug("Running command : " + String.join(" ", command));
}
ExecutorService executor = executorServiceFactory.createExecutorService();
// Builds the command to execute.
ProcessBuilder processBuilder = processBuilderFactory.createProcessBuilder();
processBuilder.command(command);
processBuilder.redirectErrorStream(true);
if (environment != null) {
processBuilder.environment().putAll(environment);
}
final Process process = processBuilder.start();
// Runs the command and streams the output.
List<String> output = new ArrayList<>();
executor.execute(outputConsumerRunnable(process, output));
int exitCode = process.waitFor();
// Shuts down the executor.
executor.shutdown();
try {
executor.awaitTermination(TIMEOUT_SECONDS, TimeUnit.SECONDS);
} catch (InterruptedException ex) {
if (logger != null) {
logger.debug("Task Executor interrupted waiting for output consumer thread");
}
}
// Stops the build if the command fails to do something, we may want to make this configurable.
if (exitCode != 0) {
throw new GradleException("command exited with non-zero exit code : " + exitCode);
}
return output;
}
示例9: read
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
public DexApplication read() throws IOException, ExecutionException {
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
return read(executor);
} finally {
executor.shutdown();
}
}
示例10: main
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
public static void main(String[] args)
{
ExecutorService exec = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++)
{
exec.execute(new SimplePriorities(Thread.MIN_PRIORITY));
}
exec.execute(new SimplePriorities(Thread.MAX_PRIORITY));
exec.shutdown();
}
示例11: testFailedCommandWithConnectionCloseCmdBehavior
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
/**
* Regression test for VSTS Bug# 3936154 - Execute a command that will result in a failure in a loop - Without the fix (disabling the command
* behavior)s, the test will not respond and timeout.
*/
@Test
@Category(value = ExcludeFromGatedCheckin.class)
public final void testFailedCommandWithConnectionCloseCmdBehavior() {
ExecutorService exec = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
try {
for (int i = 0; i < 100; i++) {
int index = i;
exec.submit(() -> {
try (MultiShardStatement stmt = shardConnection.createCommand()) {
stmt.setCommandText("select * from table_does_not_exist");
try (MultiShardResultSet sdr = stmt.executeQuery()) {
while (sdr.next()) {
}
}
}
catch (Exception ex) {
System.out.printf("Encountered exception: %1$s in iteration: %2$s \r\n", ex.toString(), index);
}
finally {
System.out.printf("Completed execution of iteration: %1$s" + "\r\n", index);
}
});
}
}
finally {
exec.shutdown();
}
}
示例12: main
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
public static void main(String[] args) throws Throwable {
final String[] algorithmNames = {
"PBKDF2WITHHMACSHA1",
"PBEWITHMD5ANDDES",
"DSA",
"SHA384WITHRSA",
"RSA",
"SHA1WITHDSA",
"SHA512WITHRSA",
"MD2WITHRSA",
"PBEWITHSHA1ANDDESEDE",
"SHA1WITHRSA",
"DIFFIEHELLMAN",
"MD5WITHRSA",
"PBEWITHSHA1ANDRC2_40",
"SHA256WITHRSA",
};
final int THREADS = 2;
final ExecutorService pool = Executors.newFixedThreadPool(THREADS);
final CountDownLatch startingGate = new CountDownLatch(THREADS);
final Runnable r = new Runnable() { public void run() {
startingGate.countDown();
do {} while (startingGate.getCount() > 0);
try {
for (String algorithmName : algorithmNames)
AlgorithmId.get(algorithmName);
} catch (Throwable fail) {
throw new AssertionError(fail);
}
}};
final ArrayList<Future<?>> futures = new ArrayList<>();
for (int i = 0; i < THREADS; i++)
futures.add(pool.submit(r));
pool.shutdown();
for (Future<?> future : futures) future.get();
}
示例13: getPage
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
/** 根据Id查询(cls返回类型Class) */
public <K> Page<K> getPage(final Page<Long> ids, final Class<K> cls) {
if (ids != null) {
Page<K> page = new Page<K>(ids.getCurrent(), ids.getSize());
page.setTotal(ids.getTotal());
final List<K> records = InstanceUtil.newArrayList();
for (int i = 0; i < ids.getRecords().size(); i++) {
records.add(null);
}
int thread = Math.min(maxThread, Math.max(1, records.size() / 2));
ExecutorService executorService = Executors.newFixedThreadPool(thread);
for (int i = 0; i < ids.getRecords().size(); i++) {
final int index = i;
executorService.execute(new Runnable() {
public void run() {
T t = queryById(ids.getRecords().get(index));
K k = InstanceUtil.to(t, cls);
records.set(index, k);
}
});
}
executorService.shutdown();
try {
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
} catch (InterruptedException e) {
logger.error("awaitTermination", "", e);
}
page.setRecords(records);
return page;
}
return new Page<K>();
}
示例14: run
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
@Override
public void run() {
ExecutorService execServ = Executors.newFixedThreadPool(THREADS_NUM);
List<Future<ModelConfigurationResult>> futures = new Vector<>();
/*for (int cI = 0; cI<steps; cI++)
for (int gammaI = 0; gammaI<steps ; gammaI++){
double c = TuneModelLibSvm.computeExpParameter(cMax, cMin, kappaC, cI, steps);
double gamma = TuneModelLibSvm.computeExpParameter(gammaMax, gammaMin, kappaGamma, gammaI, steps);
futures.add(execServ.submit(pt.cloneWithGammaC(gamma, c)));
}*/
for (int cI = 0; cI < steps; cI++) {
double c = TuneModelLibSvm.computeExpParameter(cMax, cMin, kappaC, cI, steps);
futures.add(execServ.submit(pt.cloneWithGammaC(origGamma, c)));
}
for (int gammaI = 0; gammaI < steps; gammaI++) {
double gamma = TuneModelLibSvm.computeExpParameter(gammaMax, gammaMin, kappaGamma, gammaI, steps);
futures.add(execServ.submit(pt.cloneWithGammaC(gamma, origC)));
}
futures.add(execServ.submit(pt.cloneWithGammaC(origGamma, origC)));
for (Future<ModelConfigurationResult> future : futures)
try {
ModelConfigurationResult res = future.get();
scoreBoard.add(res);
} catch (InterruptedException | ExecutionException | Error e) {
throw new RuntimeException(e);
}
execServ.shutdown();
}
示例15: testMovingBackToHigherPriority
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
@Test
public void testMovingBackToHigherPriority() {
final int parallelTasks = 10;
PriorityTaskQueue pq = new PriorityTaskQueue(parallelTasks, () -> null, s -> {
});
AtomicBoolean test = new AtomicBoolean(false);
AtomicInteger errors = new AtomicInteger();
AtomicInteger doneCounter = new AtomicInteger();
pq.addTask(10, q1 -> {
q1.addTask(9, q2 -> {
q2.addTask(7, q3 -> {
if (!test.compareAndSet(false, true)) {
errors.incrementAndGet();
}
doneCounter.incrementAndGet();
});
q2.addTask(8, q3 -> {
if (!test.compareAndSet(true, false)) {
errors.incrementAndGet();
}
doneCounter.incrementAndGet();
});
doneCounter.incrementAndGet();
});
doneCounter.incrementAndGet();
});
ExecutorService executorService = Executors.newCachedThreadPool();
Queue<Exception> exceptions = new LinkedList<>();
assertThat(
pq.executeTasksAndAwaitDone(executorService, exceptions::offer, 1, TimeUnit.SECONDS),
is(true));
assertThat(exceptions.size(), is(0));
assertThat(errors.get(), is(0));
assertThat(doneCounter.get(), is(4));
executorService.shutdown();
}