当前位置: 首页>>代码示例>>Java>>正文


Java ExecutorService.submit方法代码示例

本文整理汇总了Java中java.util.concurrent.ExecutorService.submit方法的典型用法代码示例。如果您正苦于以下问题:Java ExecutorService.submit方法的具体用法?Java ExecutorService.submit怎么用?Java ExecutorService.submit使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.util.concurrent.ExecutorService的用法示例。


在下文中一共展示了ExecutorService.submit方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: B0_warm_up

import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
@Test
public void B0_warm_up() throws InterruptedException {

    List<Dummy> result = synchronizedList(new ArrayList<>());

    ExecutorService executor = newFixedThreadPool(FIFTEEN_15);

    for (int i = 0; i < ONE_MILLION; i++) {
        executor.submit(() -> {
            String json = randomJsonPool.get(random.nextInt(ONE_MILLION));
            Payload<Dummy> payload = JSON.payload().newInstance(json, Dummy.class);
            result.add(payload.get());
            result.add(gson.fromJson(json, Dummy.class));
        });
    }

    executor.shutdown();
    executor.awaitTermination(10, SECONDS);

    assertThat(result.size()).isEqualTo(ONE_MILLION * 2);
}
 
开发者ID:juliaaano,项目名称:payload,代码行数:22,代码来源:JsonBenchmark.java

示例2: test2

import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
private static void test2() throws InterruptedException, ExecutionException {
    ExecutorService executor = Executors.newFixedThreadPool(1);

    Future<Integer> future = executor.submit(() -> {
        try {
            TimeUnit.SECONDS.sleep(1);
            return 123;
        }
        catch (InterruptedException e) {
            throw new IllegalStateException("task interrupted", e);
        }
    });

    executor.shutdownNow();
    future.get();
}
 
开发者ID:daishicheng,项目名称:outcomes,代码行数:17,代码来源:Executors2.java

示例3: StatImpl

import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
public StatImpl() {
    queue = new ConcurrentLinkedQueue<>();
    reference = new AtomicReference<>(Container.ZERO_VALUE);
    ExecutorService aThread = Executors.newSingleThreadExecutor();

    Runtime.getRuntime().addShutdownHook(new Thread(this::stop));

    // multiple producers - single consumer
    // consumer queue updates my local state
//          +----------------------------------------+
//  -------->
//  -------->                                         +------->
//  -------->
//          +----------------------------------------+
    Runnable runnable = () -> {
      while (run) {
        Integer event = queue.poll();
        if (event != null) {
          for (Container prev = reference.get();
               reference.compareAndSet(prev, prev.update(event));
               prev = prev.update(event)) {}
        }
      }
    };
    aThread.submit(runnable);
  }
 
开发者ID:kogupta,项目名称:scala-playground,代码行数:27,代码来源:StatImpl.java

示例4: arranca

import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
@Override
	public void arranca() {
        this.envioEvidencias = new EnvioInfoExtractedThread();
        ExecutorService executor = Executors.newSingleThreadExecutor();
//        this.envioEvidencias.setName(agente.getIdentAgente()+"envioEvidenciasThread");
        ejecucionHebra=executor.submit(envioEvidencias);
	}
 
开发者ID:Yarichi,项目名称:Proyecto-DASI,代码行数:8,代码来源:ProcesadorItems.java

示例5: onDirectMessagePosted

import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
private void onDirectMessagePosted(final SlackletRequest req, final SlackletResponse resp) {
	final ExecutorService executor = mService.getExecutor();
	final List<Slacklet> slackletList = mService.getSlackletList();

	for (final Slacklet slet : slackletList) {
		final Runnable r = new Runnable() {
			@Override
			public void run() {
				slet.onDirectMessagePosted(req, resp);
			}
		};
		executor.submit(r);

	}
}
 
开发者ID:riversun,项目名称:slacklet,代码行数:16,代码来源:SletListenerMessagePosted.java

示例6: localizeFiles

import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
public void localizeFiles() throws IOException {
  ThreadFactory tf = new ThreadFactoryBuilder()
      .setNameFormat("Localizer #%d").build();
  ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(
      localizeThreads, tf);
  for (LocalizationResource resource : resources) {
    UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
    Configuration conf = new Configuration();
    FSDownload fsDownload = new FSDownload(
        FileContext.getLocalFSFileContext(), ugi, conf, new Path(
            localizationDir), resource);
    newFixedThreadPool.submit(fsDownload);
  }
  newFixedThreadPool.shutdown();
}
 
开发者ID:intel-hpdd,项目名称:scheduling-connector-for-hadoop,代码行数:16,代码来源:LocalizationService.java

示例7: testSubmitRunnable

import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
/**
 * Completed submit(runnable) returns successfully
 */
public void testSubmitRunnable() throws Throwable {
    ExecutorService e = new ForkJoinPool(1);
    try (PoolCleaner cleaner = cleaner(e)) {
        Future<?> future = e.submit(new NoOpRunnable());
        assertNull(future.get());
        assertTrue(future.isDone());
        assertFalse(future.isCancelled());
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:13,代码来源:ForkJoinPoolTest.java

示例8: main

import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
public static void main(String[] args) {
    MyTask task=new MyTask("aa");
    ExecutorService es= Executors.newFixedThreadPool(5);
    for(int i=0;i<10;i++){
        es.submit(task);
    }
}
 
开发者ID:sean417,项目名称:LearningOfThinkInJava,代码行数:8,代码来源:ThreadPoolDemo.java

示例9: createProcessors

import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
public static <T> ExecutorService createProcessors(int threadCount, BlockingQueue<T> queue, Consumer<T> consumer, String name) {
    ThreadGroup threadGroup = new ThreadGroup(name + "-ThreadGroup");
    ExecutorService result = Executors.newFixedThreadPool(threadCount,
            (Runnable r) -> new Thread(threadGroup, r, name + "-Thread"));
    for (int i = 0; i < threadCount; i++) {

        result.submit(new Processor(queue, consumer, name));
    }
    return result;
}
 
开发者ID:hylkevds,项目名称:SensorThingsProcessor,代码行数:11,代码来源:ProcessorHelper.java

示例10: handshakeAsync

import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
static IOFutures<String> handshakeAsync(final BufferedSource source, final BufferedSink sink, ExecutorService ioExecutors) {
    if (PROTOCOL_NAME.length() > Byte.MAX_VALUE)
        Log.wtf(TAG, "Protocol name is too long");

    IOFutures<String> futures = new IOFutures<String>();

    futures.sender = ioExecutors.submit(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            sink.writeByte(PROTOCOL_NAME.length());
            sink.writeString(PROTOCOL_NAME, DEFAULT_CHARSET);
            sink.flush();
            return null;
        }
    });

    futures.receiver = ioExecutors.submit(new Callable<String>() {
        @Override
        public String call() throws Exception {
            byte protocolNameLength = source.readByte();
            String protocolName = source.readString(protocolNameLength, DEFAULT_CHARSET);
            if (!protocolName.equals(PROTOCOL_NAME))
                throw new IOException("Protocol \"" + protocolName + "\" not supported");
            return protocolName;
        }
    });

    return futures;
}
 
开发者ID:aarmea,项目名称:noise,代码行数:30,代码来源:StreamSync.java

示例11: testAtomic

import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
@Test
public void testAtomic() throws InterruptedException {
    ExecutorService exe = Executors.newFixedThreadPool(MAX_THREADS);
    long starttime = System.currentTimeMillis();
    AtomicThread atomic = new AtomicThread(starttime);
    for (int i = 0; i < TASK_COUNT; i++) {

        exe.submit(atomic);                                  //提交线程开始计算
    }
    cdlatomic.await();
    exe.shutdown();

}
 
开发者ID:zhangboqing,项目名称:multithread,代码行数:14,代码来源:LongAdderDemo.java

示例12: processAsync

import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
private Future<Response> processAsync(ExecutorService executor, final HttpProxyCache proxyCache, final String httpRequest) {
    return executor.submit(new Callable<Response>() {

        @Override
        public Response call() throws Exception {
            return processRequest(proxyCache, httpRequest);
        }
    });
}
 
开发者ID:Achenglove,项目名称:AndroidVideoCache,代码行数:10,代码来源:HttpProxyCacheTest.java

示例13: testSubmitCallable

import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
/**
 * Completed submit(callable) returns result
 */
public void testSubmitCallable() throws Exception {
    ExecutorService e = new DirectExecutorService();
    Future<String> future = e.submit(new StringTask());
    String result = future.get();
    assertSame(TEST_STRING, result);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:10,代码来源:AbstractExecutorServiceTest.java

示例14: testInterrupt

import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
@Test
public void testInterrupt() throws Exception {
  final ProcessBuilder pb = new ProcessBuilder(
    "java",
    "-cp",
    System.getProperty("java.class.path"),
    "VASSAL.tools.io.ProcessCallableTestBlocker"
  );

  final Process proc = pb.start();

  final ByteArrayOutputStream out = new ByteArrayOutputStream();
  final ByteArrayOutputStream err = new ByteArrayOutputStream();

  final ExecutorService exec = Executors.newCachedThreadPool();

  final InputOutputStreamPump outPump = new InputOutputStreamPump(null, out);
  final InputOutputStreamPump errPump = new InputOutputStreamPump(null, err);

  final ProcessCallable c = new ProcessCallable(proc, outPump, errPump, exec);
  final Future<Integer> f = exec.submit(c);

  f.cancel(true);

  try {
    f.get();
    fail();
  }
  catch (CancellationException e) {
    // expected
  }

  assertArrayEquals(new byte[0], out.toByteArray());
  assertArrayEquals(new byte[0], err.toByteArray());
}
 
开发者ID:ajmath,项目名称:VASSAL-src,代码行数:36,代码来源:ProcessCallableTest.java

示例15: main

import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
public static void main(String[] args) throws InterruptedException {
    PricesInfo pricesInfo = new PricesInfo();
    ExecutorService es = Executors.newFixedThreadPool(WRITER_NUM + READER_NUM);
    CountDownLatch latch = new CountDownLatch(WRITER_NUM + READER_NUM);

    long start = System.currentTimeMillis();

    for (int i = 0; i < READER_NUM; i++) {
        es.submit(() -> {
            for (int j = 0; j <= WRITER_NUM / 2; j++) {
                // 每次取值花费 1 S
                System.out.printf("%s: Price 1: %f\n", Thread.currentThread().getName(), pricesInfo.getPrice1());
                System.out.printf("%s: Price 2: %f\n", Thread.currentThread().getName(), pricesInfo.getPrice2());
            }
            latch.countDown();
        });
    }

    for (int i = 0; i < WRITER_NUM; i++) {
        es.submit(() -> {
            // 每次设置花费 1 S
            pricesInfo.setPrices(Math.random() * 10, Math.random() * 15);
            latch.countDown();
        });
        TimeUnit.SECONDS.sleep(2);
    }

    es.shutdown();
    latch.await();
    System.out.println("total cost: " + (System.currentTimeMillis() - start) + " ms");
}
 
开发者ID:firery,项目名称:java-concurrency-cheatsheet,代码行数:32,代码来源:Main.java


注:本文中的java.util.concurrent.ExecutorService.submit方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。