ExecutorService taskExecutor = Executors.newFixedThreadPool(4); while(...) { taskExecutor.execute(new MyTask()); } taskExecutor.shutdown(); try { taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { ... }
CountDownLatch latch = new CountDownLatch(totalNumberOfTasks); ExecutorService taskExecutor = Executors.newFixedThreadPool(4); while(...) { taskExecutor.execute(new MyTask()); } try { latch.await(); } catch (InterruptedException E) { // handle }
/* Get an executor service that will run a maximum of 5 threads at a time: */ ExecutorService exec = Executors.newFixedThreadPool(5); /* For all the 100 tasks to be done altogether... */ for (int i = 0; i < 100; i++) { /* ...execute the task to run concurrently as a runnable: */ exec.execute(new Runnable() { public void run() { /* do the work to be done in its own thread */ System.out.println("Running in: " + Thread.currentThread()); } }); } /* Tell the executor that after these 100 steps above, we will be done: */ exec.shutdown(); try { /* The tasks are now running concurrently. We wait until all work is done, * with a timeout of 50 seconds: */ boolean b = exec.awaitTermination(50, TimeUnit.SECONDS); /* If the execution timed out, false is returned: */ System.out.println("All done: " + b); } catch (InterruptedException e) { e.printStackTrace(); }
public class Main { private static final int NTHREDS = 10; public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(NTHREDS); for (int i = 0; i < 500; i++) { Runnable worker = new MyRunnable(10000000L + i); executor.execute(worker); } // This will make the executor accept no new threads // and finish all existing threads in the queue executor.shutdown(); // Wait until all threads are finish executor.awaitTermination(); System.out.println("Finished all threads"); } }
public void run() { System.out.println("MemcachedConnector listening on " + srv_sock.getLocalSocketAddress()); while(thread != null && Thread.currentThread().equals(thread)) { Socket client_sock=null; try { client_sock=srv_sock.accept(); // System.out.println("ACCEPT: " + client_sock.getRemoteSocketAddress()); final RequestHandler handler=new RequestHandler(client_sock); /*new Thread() { public void run() { handler.run(); } }.start(); */ thread_pool.execute(handler); } catch(ClosedSelectorException closed) { Util.close(client_sock); break; } catch(Throwable e) { } } }
public class ThreadTest { public static void main(String[] args) throws InterruptedException { ThreadTest test = new ThreadTest(); test.go(); } void go() throws InterruptedException{ ExecutorService service = Executors.newSingleThreadExecutor(); service.execute(new LongRunnable()); if(!service.awaitTermination(1000, TimeUnit.MILLISECONDS)){ System.out.println("Not finished within interval"); service.shutdownNow(); } }
@Test public void mulTest() { Executor pool = Executors.newFixedThreadPool(20); CountDownLatch encodeLatch = new CountDownLatch(1); CountDownLatch decodeLatch = new CountDownLatch(1); for (int i = 0; i < 18; i++) { pool.execute(new Worker(i, encodeLatch, decodeLatch)); } try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } encodeLatch.countDown(); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } decodeLatch.countDown(); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("end"); }
import java.util.concurrent.*; class ThreadIdTest { public static void main(String[] args) { final int numThreads = 5; ExecutorService exec = Executors.newFixedThreadPool(numThreads); for (int i=0; i<10; i++) { exec.execute(new Runnable() { public void run() { long threadId = Thread.currentThread().getId(); System.out.println("I am thread " + threadId + " of " + numThreads); } }); } exec.shutdown(); } }
ExecutorService es = Executors.newFixedThreadPool(threads); long start = System.nanoTime(); int runs = 200000; for (int i = 0; i < runs; i++) es.execute(task); for (int i = 0; i < runs; i++) queue.take(); long time = System.nanoTime() - start; System.out.printf("Time for a task to complete in a thread pool %.2f us%n", time / runs / 1000.0); es.shutdown();
ExecutorService e = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); // Do work using something like either e.execute(new Runnable() { public void run() { // do one task } });
ExecutorService e1 = Executors.newSingleThreadExecutor(); ExecutorService e2 = Executors.newSingleThreadExecutor(); e1.execute( new ExpressTask() ); e2.execute( new SequentialTask("Part-One")); e2.execute( new SequentialTask("Part-Two")); e2.execute( new SequentialTask("Part-Three")); e1.shutdown(); e2.shutdown();
System.out.println(name+" sees event!"); Executors.newFixedThreadPool(1).execute(new Runnable(){
public class Main { public static void main(String[] args) throws Exception { // the array to modify final int[] array = new int[1000]; // start the executor (that modifies the array) ExecutorService executor = Executors.newFixedThreadPool(10); for (int i = 0; i < 1000; i++) { final int c = i; executor.execute(new Runnable() { @Override public void run() { array[c] = c; } }); } // wait for all tasks to quit executor.shutdown(); while (!executor.awaitTermination(10, TimeUnit.SECONDS)); // print the array System.out.println(Arrays.toString(array)); } }
public void run(int iterations, int limit, Executor executor, Supplier<Long> latency) { AtomicInteger requests = new AtomicInteger(); AtomicInteger busy = new AtomicInteger(); AtomicInteger counter = new AtomicInteger(); Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> { System.out.println("" + counter.incrementAndGet() + " total=" + requests.getAndSet(0) + " busy=" + busy.get()); }, 1, 1, TimeUnit.SECONDS); Semaphore sem = new Semaphore(limit, true); for (int i = 0; i < iterations; i++) { requests.incrementAndGet(); busy.incrementAndGet(); executor.execute(() -> { try { sem.acquire(); TimeUnit.MILLISECONDS.sleep(latency.get()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { sem.release(); busy.decrementAndGet(); } }); } }
exec = Executors.newFixedThreadPool(size); exec.execute(new Runnable() { public void destroy() { exec.shutdown();
ExecutorService exec = Executors.newFixedThreadPool(4, new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = Executors.defaultThreadFactory().newThread(r); t.setDaemon(true); return t; } }); exec.execute(YourTaskNowWillBeDaemon);