本文整理了Java中java.util.concurrent.Executors.newSingleThreadExecutor()
方法的一些代码示例,展示了Executors.newSingleThreadExecutor()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Executors.newSingleThreadExecutor()
方法的具体详情如下:
包路径:java.util.concurrent.Executors
类名称:Executors
方法名:newSingleThreadExecutor
[英]Creates an Executor that uses a single worker thread operating off an unbounded queue. (Note however that if this single thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks.) Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time. Unlike the otherwise equivalent newFixedThreadPool(1) the returned executor is guaranteed not to be reconfigurable to use additional threads.
[中]创建一个执行器,该执行器使用在无界队列上运行的单个工作线程。(但是请注意,如果此单线程在关机之前的执行过程中由于故障而终止,则在需要执行后续任务时,将使用新线程代替它。)任务保证按顺序执行,并且在任何给定时间都不会有多个任务处于活动状态。与其他等效的newFixedThreadPool(1)不同,返回的执行器保证不可重新配置以使用其他线程。
代码示例来源:origin: neo4j/neo4j
@Deprecated
public static <T> Future<T> future( final Callable<T> task )
{
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<T> future = executor.submit( task );
executor.shutdown();
return future;
}
}
代码示例来源:origin: skylot/jadx
public synchronized Future<Boolean> process() {
if (future != null) {
return future;
}
ExecutorService shutdownExecutor = Executors.newSingleThreadExecutor();
FutureTask<Boolean> task = new ShutdownTask();
shutdownExecutor.execute(task);
shutdownExecutor.shutdown();
future = task;
return future;
}
代码示例来源:origin: prestodb/presto
@PostConstruct
public synchronized void start()
{
if (finalizerTask != null) {
return;
}
if (executor == null) {
executor = newSingleThreadExecutor(daemonThreadsNamed("FinalizerService"));
}
if (executor.isShutdown()) {
throw new IllegalStateException("Finalizer service has been destroyed");
}
finalizerTask = executor.submit(this::processFinalizerQueue);
}
代码示例来源:origin: stackoverflow.com
ExecutorService service = Executors.newSingleThreadExecutor();
try {
Runnable r = new Runnable() {
@Override
public void run() {
// Database task
}
};
Future<?> f = service.submit(r);
f.get(2, TimeUnit.MINUTES); // attempt the task for two minutes
}
catch (final InterruptedException e) {
// The thread was interrupted during sleep, wait or join
}
catch (final TimeoutException e) {
// Took too long!
}
catch (final ExecutionException e) {
// An exception from within the Runnable task
}
finally {
service.shutdown();
}
代码示例来源:origin: ethereum/ethereumj
@Test
public void interruptTest() throws InterruptedException {
ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor());
final ListenableFuture<Object> future = executor.submit(() -> {
// try {
System.out.println("Waiting");
Thread.sleep(10000);
System.out.println("Complete");
return null;
// } catch (Exception e) {
// e.printStackTrace();
// throw e;
// }
});
future.addListener(() -> {
System.out.println("Listener: " + future.isCancelled() + ", " + future.isDone());
try {
future.get();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}, MoreExecutors.directExecutor());
Thread.sleep(1000);
future.cancel(true);
}
代码示例来源:origin: ReactiveX/RxJava
@Test
public void disposeRace() {
ExecutorService exec = Executors.newSingleThreadExecutor();
final Scheduler s = Schedulers.from(exec);
try {
for (int i = 0; i < 500; i++) {
final Worker w = s.createWorker();
final AtomicInteger c = new AtomicInteger(2);
w.schedule(new Runnable() {
@Override
public void run() {
c.decrementAndGet();
while (c.get() != 0) { }
}
});
c.decrementAndGet();
while (c.get() != 0) { }
w.dispose();
}
} finally {
exec.shutdownNow();
}
}
代码示例来源:origin: shekhargulati/java8-the-missing-tutorial
public static void main(String[] args) {
CompletableFuture.completedFuture("hello");
CompletableFuture.runAsync(() -> System.out.println("hello"));
CompletableFuture.runAsync(() -> System.out.println("hello"), Executors.newSingleThreadExecutor());
CompletableFuture.supplyAsync(() -> UUID.randomUUID().toString());
CompletableFuture.supplyAsync(() -> UUID.randomUUID().toString(), Executors.newSingleThreadExecutor());
}
}
代码示例来源:origin: LeonardoZ/java-concurrency-patterns
public static void usingSingleThreadExecutor() {
System.out.println("=== SingleThreadExecutor ===");
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
singleThreadExecutor.execute(() -> System.out.println("Print this."));
singleThreadExecutor.execute(() -> System.out.println("and this one to."));
singleThreadExecutor.shutdown();
try {
singleThreadExecutor.awaitTermination(4, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("\n\n");
}
代码示例来源:origin: org.apache.commons/commons-lang3
/**
* Tries to pass a null Callable to the constructor that takes an executor.
* This should cause an exception.
*/
@Test(expected=IllegalArgumentException.class)
public void testInitExecutorNullCallable() throws InterruptedException {
final ExecutorService exec = Executors.newSingleThreadExecutor();
try {
new CallableBackgroundInitializer<Integer>(null, exec);
} finally {
exec.shutdown();
exec.awaitTermination(1, TimeUnit.SECONDS);
}
}
代码示例来源:origin: spring-projects/spring-framework
@Test
public void closeStatusChangesToSessionNotReliable() throws Exception {
BlockingSession session = new BlockingSession();
session.setId("123");
session.setOpen(true);
CountDownLatch sentMessageLatch = session.getSentMessageLatch();
int sendTimeLimit = 100;
int bufferSizeLimit = 1024;
final ConcurrentWebSocketSessionDecorator decorator =
new ConcurrentWebSocketSessionDecorator(session, sendTimeLimit, bufferSizeLimit);
Executors.newSingleThreadExecutor().submit((Runnable) () -> {
TextMessage message = new TextMessage("slow message");
try {
decorator.sendMessage(message);
}
catch (IOException e) {
e.printStackTrace();
}
});
assertTrue(sentMessageLatch.await(5, TimeUnit.SECONDS));
// ensure some send time elapses
Thread.sleep(sendTimeLimit + 100);
decorator.close(CloseStatus.PROTOCOL_ERROR);
assertEquals("CloseStatus should have changed to SESSION_NOT_RELIABLE",
CloseStatus.SESSION_NOT_RELIABLE, session.getCloseStatus());
}
代码示例来源:origin: eclipse-vertx/vert.x
@Test
public void testExecuteFromIOWorkerFromNonVertxThread() {
assertEquals("true", System.getProperty("vertx.threadChecks"));
ExecutorService a = Executors.newSingleThreadExecutor();
ContextInternal ctx = ((VertxInternal) vertx).createWorkerContext(null, new WorkerPool(a, null), null, Thread.currentThread().getContextClassLoader());
AtomicBoolean called = new AtomicBoolean();
try {
ctx.executeFromIO(v -> {
called.set(true);
});
fail();
} catch (IllegalStateException ignore) {
//
}
assertFalse(called.get());
}
代码示例来源:origin: stackoverflow.com
ExecutorService executor = Executors.newSingleThreadExecutor();
Runnable task = new Runnable() {
public void run() {
throw new RuntimeException("foo");
}
};
Future<?> future = executor.submit(task);
try {
future.get();
} catch (ExecutionException e) {
Exception rootException = e.getCause();
}
代码示例来源:origin: google/guava
ExecutorService executor = newSingleThreadExecutor();
Future<V> waiter =
executor.submit(
new Callable<V>() {
@Override
代码示例来源:origin: SonarSource/sonarqube
@Override
public void run() {
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
Future future = executor.submit(monitored::stop);
future.get(terminationTimeoutMs, TimeUnit.MILLISECONDS);
} catch (Exception e) {
LoggerFactory.getLogger(getClass()).error("Can not stop in {}ms", terminationTimeoutMs, e);
}
executor.shutdownNow();
commands.endWatch();
}
}
代码示例来源:origin: reactor/reactor-core
@Test
public void handleErrorWithJvmFatalForwardsToUncaughtHandlerFusedCallable() {
AtomicBoolean handlerCaught = new AtomicBoolean();
Scheduler scheduler = Schedulers.fromExecutorService(Executors.newSingleThreadExecutor(r -> {
Thread thread = new Thread(r);
thread.setUncaughtExceptionHandler((t, ex) -> {
handlerCaught.set(true);
System.err.println("from uncaught handler: " + ex.toString());
});
return thread;
}));
final StepVerifier stepVerifier =
StepVerifier.create(Mono.<String>fromCallable(() -> {
throw new StackOverflowError("boom");
}).subscribeOn(scheduler))
.expectFusion()
.expectErrorMessage("boom");
//the exception is still fatal, so the StepVerifier should time out.
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> stepVerifier.verify(Duration.ofMillis(100)))
.withMessageStartingWith("VerifySubscriber timed out on ");
//nonetheless, the uncaught exception handler should have been invoked
assertThat(handlerCaught).as("uncaughtExceptionHandler used").isTrue();
}
代码示例来源:origin: ReactiveX/RxJava
@Test
public void disposeRace() {
ExecutorService exec = Executors.newSingleThreadExecutor();
final Scheduler s = Schedulers.from(exec, true);
try {
for (int i = 0; i < 500; i++) {
final Worker w = s.createWorker();
final AtomicInteger c = new AtomicInteger(2);
w.schedule(new Runnable() {
@Override
public void run() {
c.decrementAndGet();
while (c.get() != 0) { }
}
});
c.decrementAndGet();
while (c.get() != 0) { }
w.dispose();
}
} finally {
exec.shutdownNow();
}
}
代码示例来源:origin: stackoverflow.com
ExecutorService exec = Executors.newSingleThreadExecutor();
CompletableFuture<Integer> f = CompletableFuture.supplyAsync(new MySupplier(), exec);
System.out.println(f.isDone()); // False
CompletableFuture<Integer> f2 = f.thenApply(new PlusOne());
System.out.println(f2.get()); // Waits until the "calculation" is done, then prints 2
代码示例来源:origin: LeonardoZ/java-concurrency-patterns
public static void main(String[] args) {
Callable<Integer> callable = () -> {
int random = new Random().nextInt(10) * 100;
System.out.println("Preparing to execute");
Thread.sleep(random);
System.out.println("Executed - " + random);
return random;
};
FutureTask<Integer> futureTask = new FutureTask<>(callable);
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(futureTask);
try {
Integer value = futureTask.get(2, TimeUnit.SECONDS);
System.out.println("Value is " + value);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
e.printStackTrace();
}
executor.shutdown();
}
代码示例来源:origin: eclipse-vertx/vert.x
@Test
public void testDeliverPausedBufferWhenResumeOnOtherThread() throws Exception {
ExecutorService exec = Executors.newSingleThreadExecutor();
try {
testDeliverPausedBufferWhenResume(block -> exec.execute(() -> {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
fail(e);
Thread.currentThread().interrupt();
}
block.run();
}));
} finally {
exec.shutdown();
}
}
代码示例来源:origin: docker-java/docker-java
public static <T> Future<Void> startAsyncProcessing(AbstractCallbackNotifier<T> callbackNotifier) {
ExecutorService executorService = Executors.newSingleThreadExecutor(FACTORY);
Future<Void> response = executorService.submit(callbackNotifier);
executorService.shutdown();
return response;
}
}
内容来源于网络,如有侵权,请联系作者删除!