import java.util.concurrent.atomic.AtomicInteger; public class AtomicVariableExample { private static AtomicInteger counter = new AtomicInteger(0); public static void main(String[] args) { for (int i = 0; i < 10; i++) { new Thread(() -> { for (int j = 0; j < 1000; j++) { counter.incrementAndGet(); } }).start(); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Counter: " + counter.get()); } } import java.util.concurrent.ConcurrentHashMap; public class ConcurrentCollectionExample { private static ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>(); public static void main(String[] args) { map.put("A", 1); map.put("B", 2); map.put("C", 3); new Thread(() -> { map.put("D", 4); }).start(); new Thread(() -> { System.out.println(map.get("A")); }).start(); } } import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadPoolExample { public static void main(String[] args) { ExecutorService executorService = Executors.newFixedThreadPool(5); for (int i = 0; i < 10; i++) { executorService.submit(() -> { System.out.println("Thread: " + Thread.currentThread().getName()); }); } executorService.shutdown(); } }


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