當前位置: 首頁>>代碼示例>>Java>>正文


Java Executors.newCachedThreadPool方法代碼示例

本文整理匯總了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;
}
 
開發者ID:pimps,項目名稱:ysoserial-modified,代碼行數:23,代碼來源:JenkinsCLI.java

示例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);
}
 
開發者ID:PacktPublishing,項目名稱:Java-9-Cookbook,代碼行數:20,代碼來源:Chapter07Concurrency03.java

示例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;
    }
 
開發者ID:CrypDist,項目名稱:CrypDist,代碼行數:25,代碼來源:Client.java

示例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);
}
 
開發者ID:DysaniazzZ,項目名稱:ArtOfAndroid,代碼行數:22,代碼來源:MainActivity.java

示例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();
   } 
}
 
開發者ID:cleitonferreira,項目名稱:LivroJavaComoProgramar10Edicao,代碼行數:37,代碼來源:SharedArrayTest.java

示例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");

}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:37,代碼來源:Deadlock.java

示例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();
        }

    }
 
開發者ID:stacs-srg,項目名稱:shabdiz,代碼行數:33,代碼來源:ExperimentManager.java

示例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;
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:30,代碼來源:JdiInitiator.java

示例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);
    }
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:54,代碼來源:LightWeightHttpServer.java

示例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));
}
 
開發者ID:baohongfei,項目名稱:think-in-java,代碼行數:9,代碼來源:PriorityBlockingQueueDemo.java

示例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!");
	}
}
 
開發者ID:baohongfei,項目名稱:think-in-java,代碼行數:13,代碼來源:NaiveExceptionHandling.java

示例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
}
 
開發者ID:baohongfei,項目名稱:think-in-java,代碼行數:11,代碼來源:ThreadLocalVariableHolder.java

示例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;
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:10,代碼來源:MockTcpTransport.java

示例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);
}
 
開發者ID:hgs1217,項目名稱:Paper-Melody,代碼行數:16,代碼來源:RetrofitClient.java

示例15: startExecutor

import java.util.concurrent.Executors; //導入方法依賴的package包/類
@PostConstruct
public void startExecutor() {
    readResultsProcessingExecutor = Executors.newCachedThreadPool();
}
 
開發者ID:osswangxining,項目名稱:iotplatform,代碼行數:5,代碼來源:BaseAlarmService.java


注:本文中的java.util.concurrent.Executors.newCachedThreadPool方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。