本文整理汇总了Java中java.util.concurrent.Executors.newCachedThreadPool方法的典型用法代码示例。如果您正苦于以下问题:Java Executors.newCachedThreadPool方法的具体用法?Java Executors.newCachedThreadPool怎么用?Java Executors.newCachedThreadPool使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.util.concurrent.Executors
的用法示例。
在下文中一共展示了Executors.newCachedThreadPool方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: openChannel
import java.util.concurrent.Executors; //导入方法依赖的package包/类
public static Channel openChannel ( InetSocketAddress isa ) throws IOException, SocketException {
System.err.println("* Opening socket " + isa);
Socket s = SocketFactory.getDefault().createSocket(isa.getAddress(), isa.getPort());
s.setKeepAlive(true);
s.setTcpNoDelay(true);
System.err.println("* Opening channel");
OutputStream outputStream = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(outputStream);
dos.writeUTF("Protocol:CLI-connect");
ExecutorService cp = Executors.newCachedThreadPool(new ThreadFactory() {
public Thread newThread ( Runnable r ) {
Thread t = new Thread(r, "Channel");
t.setDaemon(true);
return t;
}
});
Channel c = new ChannelBuilder("EXPLOIT", cp).withMode(Mode.BINARY).build(s.getInputStream(), outputStream);
System.err.println("* Channel open");
return c;
}
示例2: demo5_submitCallableGetResult
import java.util.concurrent.Executors; //导入方法依赖的package包/类
private static void demo5_submitCallableGetResult() {
CallableWorker callable = new CallableWorkerImpl("One", 2);
System.out.println();
System.out.println("Executors.newSingleThreadExecutor():");
ExecutorService execService = Executors.newSingleThreadExecutor();
submitCallableGetResult(execService, 1, callable);
System.out.println();
System.out.println("Executors.newCachedThreadPool():");
execService = Executors.newCachedThreadPool();
submitCallableGetResult(execService, 1, callable);
System.out.println();
int poolSize = 3;
System.out.println("Executors.newFixedThreadPool(" + poolSize + "):");
execService = Executors.newFixedThreadPool(poolSize);
submitCallableGetResult(execService, 1, callable);
}
示例3: broadCastMessageResponseWithIp
import java.util.concurrent.Executors; //导入方法依赖的package包/类
public HashMap<String,String> broadCastMessageResponseWithIp(String message) {
ExecutorService executor = Executors.newCachedThreadPool();
HashMap<Peer,Future<String>> futures = new HashMap<>();
for(Peer peer:peerList.keySet()) {
Callable<String> task = new ResponsedMessageTask(peer,message);
Future<String> future = executor.submit(task);
futures.put(peer,future);
}
HashMap<String,String> result = new HashMap<>();
for(Map.Entry<Peer,Future<String>> entry : futures.entrySet()) {
try {
String res = entry.getValue().get();
if(res != null && !res.equals(""))
result.put(entry.getKey().getAddress().toString(),res);
} catch (Exception e) {}
}
return result;
}
示例4: runThreadPool
import java.util.concurrent.Executors; //导入方法依赖的package包/类
private void runThreadPool() {
Runnable command = new Runnable(){
@Override
public void run() {
Log.d(TAG, Thread.currentThread().getName());
}
};
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
fixedThreadPool.execute(command);
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
cachedThreadPool.execute(command);
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);
//scheduledThreadPool.schedule(command, 2, TimeUnit.SECONDS); //延迟2秒后执行
scheduledThreadPool.scheduleAtFixedRate(command, 10, 2000, TimeUnit.MILLISECONDS); //延迟10ms后,每隔1000ms执行一次
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
singleThreadExecutor.execute(command);
}
示例5: main
import java.util.concurrent.Executors; //导入方法依赖的package包/类
public static void main(String[] arg)
{
// construct the shared object
SimpleArray sharedSimpleArray = new SimpleArray(6);
// create two tasks to write to the shared SimpleArray
ArrayWriter writer1 = new ArrayWriter(1, sharedSimpleArray);
ArrayWriter writer2 = new ArrayWriter(11, sharedSimpleArray);
// execute the tasks with an ExecutorService
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(writer1);
executorService.execute(writer2);
executorService.shutdown();
try
{
// wait 1 minute for both writers to finish executing
boolean tasksEnded =
executorService.awaitTermination(1, TimeUnit.MINUTES);
if (tasksEnded)
{
System.out.printf("%nContents of SimpleArray:%n");
System.out.println(sharedSimpleArray); // print contents
}
else
System.out.println(
"Timed out while waiting for tasks to finish.");
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
示例6: main
import java.util.concurrent.Executors; //导入方法依赖的package包/类
public static void main (String[] args) throws Exception {
Handler handler = new Handler();
InetSocketAddress addr = new InetSocketAddress (0);
HttpServer server = HttpServer.create(addr, 0);
HttpContext ctx = server.createContext("/test", handler);
BasicAuthenticator a = new BasicAuthenticator("[email protected]") {
@Override
public boolean checkCredentials (String username, String pw) {
return "fred".equals(username) && pw.charAt(0) == 'x';
}
};
ctx.setAuthenticator(a);
ExecutorService executor = Executors.newCachedThreadPool();
server.setExecutor(executor);
server.start ();
java.net.Authenticator.setDefault(new MyAuthenticator());
System.out.print("Deadlock: " );
for (int i=0; i<2; i++) {
Runner t = new Runner(server, i);
t.start();
t.join();
}
server.stop(2);
executor.shutdown();
if (error) {
throw new RuntimeException("test failed error");
}
if (count != 2) {
throw new RuntimeException("test failed count = " + count);
}
System.out.println("OK");
}
示例7: clearCachedShabdizFilesOnAllHosts
import java.util.concurrent.Executors; //导入方法依赖的package包/类
protected void clearCachedShabdizFilesOnAllHosts(ApplicationNetwork network) throws IOException, InterruptedException, TimeoutException, ExecutionException {
LOGGER.info("Attempting to remove all shabdiz cached files on {} hosts", network.size());
final ExecutorService executor = Executors.newCachedThreadPool();
try {
final List<CompletableFuture<Void>> future_deletions = new ArrayList<>();
for (final ApplicationDescriptor descriptor : network) {
final Host host = descriptor.getHost();
final CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
final String host_name = host.getName();
LOGGER.info("removing shabdiz cached files on {}", host_name);
try {
AgentBasedJavaProcessBuilder.clearCachedFilesOnHost(host);
LOGGER.info("done removing shabdiz cached files on {}", host_name);
}
catch (final Exception e) {
LOGGER.error("failed to remove shabdiz cached files on " + host_name, e);
throw new RuntimeException(e);
}
}, executor);
future_deletions.add(future);
}
CompletableFuture.allOf(future_deletions.toArray(new CompletableFuture[future_deletions.size()])).get(CACHE_DELETION_TIMEOUT.getLength(), CACHE_DELETION_TIMEOUT.getTimeUnit());
}
finally {
executor.shutdownNow();
}
}
示例8: timedVirtualMachineCreation
import java.util.concurrent.Executors; //导入方法依赖的package包/类
VirtualMachine timedVirtualMachineCreation(Callable<VirtualMachine> creator,
Callable<Integer> processComplete) throws Exception {
VirtualMachine result;
ExecutorService executor = Executors.newCachedThreadPool(runnable -> {
Thread thread = Executors.defaultThreadFactory().newThread(runnable);
thread.setDaemon(true);
return thread;
});
try {
Future<VirtualMachine> future = executor.submit(creator);
if (processComplete != null) {
executor.submit(() -> {
Integer i = processComplete.call();
future.cancel(true);
return i;
});
}
try {
result = future.get(connectTimeout, TimeUnit.MILLISECONDS);
} catch (TimeoutException ex) {
future.cancel(true);
throw ex;
}
} finally {
executor.shutdownNow();
}
return result;
}
示例9: initServer
import java.util.concurrent.Executors; //导入方法依赖的package包/类
public static void initServer() throws IOException {
Logger logger = Logger.getLogger("com.sun.net.httpserver");
ConsoleHandler ch = new ConsoleHandler();
logger.setLevel(Level.ALL);
ch.setLevel(Level.ALL);
logger.addHandler(ch);
String root = System.getProperty("test.src") + "/docs";
InetSocketAddress addr = new InetSocketAddress(0);
httpServer = HttpServer.create(addr, 0);
if (httpServer instanceof HttpsServer) {
throw new RuntimeException("should not be httpsserver");
}
httpsServer = HttpsServer.create(addr, 0);
HttpHandler h = new FileServerHandler(root);
HttpContext c1 = httpServer.createContext("/files", h);
HttpContext c2 = httpsServer.createContext("/files", h);
HttpContext c3 = httpServer.createContext("/echo", new EchoHandler());
redirectHandler = new RedirectHandler("/redirect");
redirectHandlerSecure = new RedirectHandler("/redirect");
HttpContext c4 = httpServer.createContext("/redirect", redirectHandler);
HttpContext c41 = httpsServer.createContext("/redirect", redirectHandlerSecure);
HttpContext c5 = httpsServer.createContext("/echo", new EchoHandler());
HttpContext c6 = httpServer.createContext("/keepalive", new KeepAliveHandler());
redirectErrorHandler = new RedirectErrorHandler("/redirecterror");
redirectErrorHandlerSecure = new RedirectErrorHandler("/redirecterror");
HttpContext c7 = httpServer.createContext("/redirecterror", redirectErrorHandler);
HttpContext c71 = httpsServer.createContext("/redirecterror", redirectErrorHandlerSecure);
delayHandler = new DelayHandler();
HttpContext c8 = httpServer.createContext("/delay", delayHandler);
HttpContext c81 = httpsServer.createContext("/delay", delayHandler);
executor = Executors.newCachedThreadPool();
httpServer.setExecutor(executor);
httpsServer.setExecutor(executor);
ctx = new SimpleSSLContext().get();
httpsServer.setHttpsConfigurator(new HttpsConfigurator(ctx));
httpServer.start();
httpsServer.start();
port = httpServer.getAddress().getPort();
System.out.println("HTTP server port = " + port);
httpsport = httpsServer.getAddress().getPort();
System.out.println("HTTPS server port = " + httpsport);
httproot = "http://127.0.0.1:" + port + "/";
httpsroot = "https://127.0.0.1:" + httpsport + "/";
proxy = new ProxyServer(0, false);
proxyPort = proxy.getPort();
System.out.println("Proxy port = " + proxyPort);
}
示例10: main
import java.util.concurrent.Executors; //导入方法依赖的package包/类
public static void main(String[] args) throws Exception
{
Random rand = new Random(47);
ExecutorService exec = Executors.newCachedThreadPool();
PriorityBlockingQueue<Runnable> queue = new PriorityBlockingQueue<Runnable>();
exec.execute(new PrioritizedTaskProducer(queue, exec));
exec.execute(new PrioritizedTaskConsumer(queue));
}
示例11: main
import java.util.concurrent.Executors; //导入方法依赖的package包/类
public static void main(String[] args)
{
try
{
ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(new ExceptionThread());
} catch (RuntimeException ue)
{
// This statement will NOT execute!
System.out.println("Exception has been handled!");
}
}
示例12: main
import java.util.concurrent.Executors; //导入方法依赖的package包/类
public static void main(String[] args) throws Exception
{
ExecutorService exec = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++)
{
exec.execute(new Accessor(i));
}
TimeUnit.SECONDS.sleep(3); // Run for a while
exec.shutdownNow(); // All Accessors will quit
}
示例13: MockTcpTransport
import java.util.concurrent.Executors; //导入方法依赖的package包/类
public MockTcpTransport(Settings settings, ThreadPool threadPool, BigArrays bigArrays,
CircuitBreakerService circuitBreakerService, NamedWriteableRegistry namedWriteableRegistry,
NetworkService networkService, Version mockVersion) {
super("mock-tcp-transport", settings, threadPool, bigArrays, circuitBreakerService, namedWriteableRegistry, networkService);
// we have our own crazy cached threadpool this one is not bounded at all...
// using the ES thread factory here is crucial for tests otherwise disruption tests won't block that thread
executor = Executors.newCachedThreadPool(EsExecutors.daemonThreadFactory(settings, Transports.TEST_MOCK_TRANSPORT_THREAD_PREFIX));
this.mockVersion = mockVersion;
}
示例14: updateBaseUrl
import java.util.concurrent.Executors; //导入方法依赖的package包/类
public static void updateBaseUrl(String baseUrl) {
BASE_URL = baseUrl;
Executor executor = Executors.newCachedThreadPool();
final Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new GsonDateTypeAdapter()).create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.callbackExecutor(executor)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(OkHttpProvider.getInstance())
.build();
socialSystemAPI = retrofit.create(SocialSystemAPI.class);
}
示例15: startExecutor
import java.util.concurrent.Executors; //导入方法依赖的package包/类
@PostConstruct
public void startExecutor() {
readResultsProcessingExecutor = Executors.newCachedThreadPool();
}