本文整理汇总了Java中java.util.concurrent.ExecutorService类的典型用法代码示例。如果您正苦于以下问题:Java ExecutorService类的具体用法?Java ExecutorService怎么用?Java ExecutorService使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ExecutorService类属于java.util.concurrent包,在下文中一共展示了ExecutorService类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: setUp
import java.util.concurrent.ExecutorService; //导入依赖的package包/类
@Override protected void setUp() {
final ExecutorService executor = Executors.newSingleThreadExecutor();
tearDownStack.addTearDown(new TearDown() {
@Override
public void tearDown() {
executor.shutdownNow();
}
});
sleeper = new SleepingRunnable(1000);
delayedFuture = executor.submit(sleeper, true);
tearDownStack.addTearDown(new TearDown() {
@Override
public void tearDown() {
Thread.interrupted();
}
});
}
示例2: getTHsHaServer
import java.util.concurrent.ExecutorService; //导入依赖的package包/类
private static TServer getTHsHaServer(TProtocolFactory protocolFactory,
TProcessor processor, TTransportFactory transportFactory,
int workerThreads,
InetSocketAddress inetSocketAddress, ThriftMetrics metrics)
throws TTransportException {
TNonblockingServerTransport serverTransport = new TNonblockingServerSocket(inetSocketAddress);
log.info("starting HBase HsHA Thrift server on " + inetSocketAddress.toString());
THsHaServer.Args serverArgs = new THsHaServer.Args(serverTransport);
if (workerThreads > 0) {
// Could support the min & max threads, avoiding to preserve existing functionality.
serverArgs.minWorkerThreads(workerThreads).maxWorkerThreads(workerThreads);
}
ExecutorService executorService = createExecutor(
workerThreads, metrics);
serverArgs.executorService(executorService);
serverArgs.processor(processor);
serverArgs.transportFactory(transportFactory);
serverArgs.protocolFactory(protocolFactory);
return new THsHaServer(serverArgs);
}
示例3: shutdownAndAwaitTermination
import java.util.concurrent.ExecutorService; //导入依赖的package包/类
/**
* from javase7 doc
*
* @param pool
*/
private void shutdownAndAwaitTermination(ExecutorService pool) {
pool.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(5, TimeUnit.SECONDS)) {
pool.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!pool.awaitTermination(5, TimeUnit.SECONDS))
System.err.println("Pool did not terminate");
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
pool.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}
示例4: explore
import java.util.concurrent.ExecutorService; //导入依赖的package包/类
/**
* Gather ResourceSync Framework documents from a source in ResultIndexes.
*
* @param url the starting url to explore
* @return List of resultIndexes of the exploration
* @throws URISyntaxException if the url could not be converted to a URI.
* @throws InterruptedException at Executor interrupts.
*/
public List<ResultIndex> explore(String url) throws URISyntaxException, InterruptedException {
URI uri = new URI(url);
ExecutorService executor = Executors.newWorkStealingPool();
List<Callable<ResultIndex>> callables = new ArrayList<>();
callables.add(() -> exploreWellKnown(uri));
callables.add(() -> exploreLinks(uri));
callables.add(() -> exploreRobotsTxt(uri));
callables.add(() -> exploreRsDocumentUri(uri));
return executor.invokeAll(callables)
.stream()
.map(future -> {
try {
return future.get();
} catch (Exception e) {
throw new IllegalStateException(e);
}
})
.collect(Collectors.toList());
}
示例5: create
import java.util.concurrent.ExecutorService; //导入依赖的package包/类
/**
* Constructs a new watcher for copy operation, and then immediately submits
* it to the thread pool.
*
* @param manager
* The {@link TransferManager} that owns this copy request.
* @param threadPool
* The {@link ExecutorService} to which we should submit new
* tasks.
* @param multipartCopyCallable
* The callable responsible for processing the copy
* asynchronously
* @param copyObjectRequest
* The original CopyObject request
*/
public static CopyMonitor create(
TransferManager manager,
CopyImpl transfer,
ExecutorService threadPool,
CopyCallable multipartCopyCallable,
CopyObjectRequest copyObjectRequest,
ProgressListenerChain progressListenerChain) {
CopyMonitor copyMonitor = new CopyMonitor(manager, transfer,
threadPool, multipartCopyCallable, copyObjectRequest,
progressListenerChain);
Future<CopyResult> thisFuture = threadPool.submit(copyMonitor);
// Use an atomic compareAndSet to prevent a possible race between the
// setting of the CopyMonitor's futureReference, and setting the
// CompleteMultipartCopy's futureReference within the call() method.
// We only want to set the futureReference to CopyMonitor's futureReference if the
// current value is null, otherwise the futureReference that's set is
// CompleteMultipartCopy's which is ultimately what we want.
copyMonitor.futureReference.compareAndSet(null, thisFuture);
return copyMonitor;
}
示例6: BackgroundOperation
import java.util.concurrent.ExecutorService; //导入依赖的package包/类
/**
* Runs an operation in the background in a separate thread.
* The execution is started immediately.
*
* @param operation The operation to execute.
*/
public BackgroundOperation(final Operation<T> operation)
{
ApfloatContext ctx = ApfloatContext.getContext();
ExecutorService executorService = ctx.getExecutorService();
Callable<T> callable = new Callable<T>()
{
public T call()
{
return operation.execute();
}
};
this.future = executorService.submit(callable);
}
示例7: main
import java.util.concurrent.ExecutorService; //导入依赖的package包/类
public static void main(String[] args) throws Exception {
try (Server server = new Server()) {
URI uri = new URI("http://127.0.0.1:" + server.getPort() + "/");
// sanity
success(uri, new StringRequestBody(STRING_BODY, 0));
success(uri, new ByteArrayRequestBody(BYTE_ARRAY_BODY, 0));
success(uri, new FileRequestBody(FILE_BODY, 0));
for (int i=1; i< BODY_OFFSETS.length; i++) {
failureBlocking(uri, new StringRequestBody(STRING_BODY, BODY_OFFSETS[i]));
failureBlocking(uri, new ByteArrayRequestBody(BYTE_ARRAY_BODY, BODY_OFFSETS[i]));
failureBlocking(uri, new FileRequestBody(FILE_BODY, BODY_OFFSETS[i]));
failureNonBlocking(uri, new StringRequestBody(STRING_BODY, BODY_OFFSETS[i]));
failureNonBlocking(uri, new ByteArrayRequestBody(BYTE_ARRAY_BODY, BODY_OFFSETS[i]));
failureNonBlocking(uri, new FileRequestBody(FILE_BODY, BODY_OFFSETS[i]));
}
} finally {
Executor def = defaultClient().executor();
if (def instanceof ExecutorService) {
((ExecutorService)def).shutdownNow();
}
}
}
示例8: runTest
import java.util.concurrent.ExecutorService; //导入依赖的package包/类
public void runTest()
{
ScheduledExecutorService s=new ScheduledThreadPoolExecutor(2, new NamedThreadFactory("Scheduled"));
ExecutorService es=Executors.newCachedThreadPool();
es.execute(this::writeTest);
es.execute(this::writeTest);
es.execute(this::writeTest);
es.execute(this::writeTest);
es.execute(this::readTest);
es.execute(this::readTest);
es.execute(this::readTest);
es.execute(this::readTest);
es.execute(this::readTest);
es.execute(this::readTest);
s.scheduleAtFixedRate(this::printInfo,5, 5, TimeUnit.SECONDS);
}
示例9: start
import java.util.concurrent.ExecutorService; //导入依赖的package包/类
void start() {
new Thread(
() -> {
ExecutorService executorService = Executors.newCachedThreadPool();
try (ServerSocket serverSocket =
new ServerSocket(port, 0, InetAddress.getLoopbackAddress())) {
while (true) {
Socket socket = serverSocket.accept();
executorService.execute(() -> process(socket));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
})
.start();
}
示例10: generateCMAX_SETs
import java.util.concurrent.ExecutorService; //导入依赖的package包/类
private void generateCMAX_SETs() throws AlgorithmExecutionException {
if (this.optimize()) {
this.cmaxSet = new CopyOnWriteArrayList<CMAX_SET>();
ExecutorService exec = this.getExecuter();
for (int i = 0; i < this.numberOfAttributes; ++i) {
exec.execute(new CMAX_SET_JOB(i));
}
this.awaitExecuter(exec);
} else {
this.cmaxSet = new LinkedList<CMAX_SET>();
for (int i = 0; i < this.numberOfAttributes; ++i) {
executeCMAX_SET_Task(i);
}
}
}
示例11: main
import java.util.concurrent.ExecutorService; //导入依赖的package包/类
public static void main(String[] args) throws InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(300);
for(int i=0;i<10000;i++){
pool.execute(new Runnable() {
@Override
public void run() {
try {
executeHttp();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
Thread.sleep(1000000L);
}
示例12: testThreadPool2
import java.util.concurrent.ExecutorService; //导入依赖的package包/类
public void testThreadPool2() {
System.out.println();
ExecutorService service = Executors.newFixedThreadPool(2);
for (int i = 0; i < 10; i++) {
service.submit(new SimpleThread2(i));
}
try {
Thread.sleep(5 * 1000);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
service.shutdown();
}
示例13: close
import java.util.concurrent.ExecutorService; //导入依赖的package包/类
public void close() {
try {
if (executor instanceof ExecutorService) {
((ExecutorService)executor).shutdown();
}
} catch (Throwable t) {
logger.warn("fail to destroy thread pool of server: " + t.getMessage(), t);
}
}
示例14: AbstractServer
import java.util.concurrent.ExecutorService; //导入依赖的package包/类
public AbstractServer(URL url, ChannelHandler handler) throws RemotingException {
super(url, handler);
localAddress = getUrl().toInetSocketAddress();
String host = url.getParameter(Constants.ANYHOST_KEY, false)
|| NetUtils.isInvalidLocalHost(getUrl().getHost())
? NetUtils.ANYHOST : getUrl().getHost();
bindAddress = new InetSocketAddress(host, getUrl().getPort());
this.accepts = url.getParameter(Constants.ACCEPTS_KEY, Constants.DEFAULT_ACCEPTS);
this.idleTimeout = url.getParameter(Constants.IDLE_TIMEOUT_KEY, Constants.DEFAULT_IDLE_TIMEOUT);
try {
doOpen();
if (logger.isInfoEnabled()) {
logger.info("Start " + getClass().getSimpleName() + " bind " + getBindAddress() + ", export " + getLocalAddress());
}
} catch (Throwable t) {
throw new RemotingException(url.toInetSocketAddress(), null, "Failed to bind " + getClass().getSimpleName()
+ " on " + getLocalAddress() + ", cause: " + t.getMessage(), t);
}
executor = (ExecutorService) ExtensionLoader.getExtensionLoader(DataStore.class)
.getDefaultExtension().get(Constants.EXECUTOR_SERVICE_COMPONENT_KEY, Integer.toString(url.getPort()));
}
示例15: processBatchCallback
import java.util.concurrent.ExecutorService; //导入依赖的package包/类
@Override
@Deprecated
public <R> void processBatchCallback(
List<? extends Row> list,
byte[] tableName,
ExecutorService pool,
Object[] results,
Batch.Callback<R> callback)
throws IOException, InterruptedException {
processBatchCallback(list, TableName.valueOf(tableName), pool, results, callback);
}