import com.atlassian.util.concurrent.*; import java.util.concurrent.*; public class ThreadPoolExample { public static void main(String[] args) { ExecutorService executor = Executors.newCachedThreadPool(); ConcurrentHashSet<String> set = new ConcurrentHashSet<String>(); Semaphore semaphore = new Semaphore(10); for (int i = 0; i < 100; i++) { executor.submit(() -> { try { semaphore.acquire(); set.add(Thread.currentThread().getName()); Thread.sleep(100); semaphore.release(); } catch (InterruptedException e) { e.printStackTrace(); } }); } executor.shutdown(); try { executor.awaitTermination(1, TimeUnit.MINUTES); } catch (InterruptedException e) { e.printStackTrace(); } set.forEach(System.out::println); } }


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