import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadPoolExample { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(5); for (int i = 0; i < 10; i++) { Runnable worker = new WorkerThread("" + i); executor.execute(worker); } executor.shutdown(); while (!executor.isTerminated()) { } System.out.println("Finished all threads"); } } class WorkerThread implements Runnable { private String message; public WorkerThread(String s){ this.message=s; } public void run() { System.out.println(Thread.currentThread().getName()+" (Start) message = "+message); processMessage(); System.out.println(Thread.currentThread().getName()+" (End)"); } private void processMessage() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import java.util.concurrent.TimeUnit; public class CacheExample { public static void main(String[] args) { LoadingCache<String, String> cache = CacheBuilder.newBuilder() .maximumSize(100) .expireAfterWrite(10, TimeUnit.MINUTES) .build( new CacheLoader<String, String>() { public String load(String key) throws Exception { } } ); try { } catch (Exception e) { e.printStackTrace(); } } private static String getFromDatabase(String key) { System.out.println("Fetching data from database for key: " + key); // ... return "value1"; } } import java.util.concurrent.CompletableFuture; public class AsyncExample { public static void main(String[] args) { CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { return "hello"; }); CompletableFuture<String> newFuture = future.thenApplyAsync(str -> { return str.toUpperCase(); }); newFuture.thenAccept(result -> { System.out.println("Result: " + result); }); } }


上一篇:
下一篇:
切换中文