1. 并发编程
1.1 并发的概念
- 并发:指程序中多个任务同时进行,目的是提高程序的执行效率和资源利用率。
- 多线程:Java 中实现并发编程的基础。
1.2 创建线程的方式
-
继承 Thread 类:
public class MyThread extends Thread { public void run() { System.out.println("Thread is running"); } } public class Main { public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); } }
-
实现 Runnable 接口:
public class MyRunnable implements Runnable { public void run() { System.out.println("Thread is running"); } } public class Main { public static void main(String[] args) { Thread thread = new Thread(new MyRunnable()); thread.start(); } }
1.3 线程同步
- synchronized 关键字:确保多线程环境下的资源访问是安全的。
public class Counter { private int count = 0; public synchronized void increment() { count++; } public int getCount() { return count; } } public class Main { public static void main(String[] args) throws InterruptedException { Counter counter = new Counter(); Thread t1 = new Thread(() -> { for (int i = 0; i < 1000; i++) { counter.increment(); } }); Thread t2 = new Thread(() -> { for (int i = 0; i < 1000; i++) { counter.increment(); } }); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("Count: " + counter.getCount()); } }
1.4 线程通信
- wait() 和 notify() 方法:实现线程间的通信。
public class Main { public static void main(String[] args) { Message message = new Message("Process it"); Waiter waiter = new Waiter(message); new Thread(waiter, "waiter").start(); Notifier notifier = new Notifier(message); new Thread(notifier, "notifier").start(); } } class Message { private String msg; public Message(String str) { this.msg = str; } public String getMsg() { return msg; } public void setMsg(String str) { this.msg = str; } } class Waiter implements Runnable { private Message msg; public Waiter(Message m) { this.msg = m; } public void run() { synchronized (msg) { try { System.out.println("Waiter is waiting..."); msg.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Waiter received message: " + msg.getMsg()); } } } class Notifier implements Runnable { private Message msg; public Notifier(Message msg) { this.msg = msg; } public void run() { synchronized (msg) { msg.setMsg("Notifier has finished processing"); msg.notify(); } } }
2. 高级集合框架
2.1 Concurrent 集合
-
ConcurrentHashMap:线程安全的哈希表。
import java.util.concurrent.ConcurrentHashMap; public class Main { public static void main(String[] args) { ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>(); map.put("1", "One"); map.put("2", "Two"); map.forEach((key, value) -> System.out.println(key + ": " + value)); } }
-
CopyOnWriteArrayList:线程安全的 ArrayList。
import java.util.concurrent.CopyOnWriteArrayList; public class Main { public static void main(String[] args) { CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>(); list.add("One"); list.add("Two"); list.forEach(System.out::println); } }
2.2 BlockingQueue
- ArrayBlockingQueue:有界阻塞队列。
import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; public class Main { public static void main(String[] args) throws InterruptedException { BlockingQueue<String> queue = new ArrayBlockingQueue<>(2); queue.put("One"); queue.put("Two"); System.out.println(queue.take()); System.out.println(queue.take()); } }
3. CompletableFuture
3.1 CompletableFuture 的概念
- CompletableFuture:用于异步编程的类,提供了处理异步任务的方法。
3.2 使用 CompletableFuture
- 示例:
import java.util.concurrent.CompletableFuture; public class Main { public static void main(String[] args) { CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } return "Hello, World!"; }); future.thenAccept(result -> System.out.println("Result: " + result)); System.out.println("Main thread is running..."); } }
4. Fork/Join 框架
4.1 Fork/Join 框架的概念
- Fork/Join 框架:用于并行执行任务,将大任务拆分成小任务。
4.2 使用 Fork/Join 框架
- 示例:
import java.util.concurrent.RecursiveTask; import java.util.concurrent.ForkJoinPool; public class Main { public static void main(String[] args) { ForkJoinPool pool = new ForkJoinPool(); Fibonacci task = new Fibonacci(10); int result = pool.invoke(task); System.out.println("Fibonacci result: " + result); } } class Fibonacci extends RecursiveTask<Integer> { private final int n; Fibonacci(int n) { this.n = n; } protected Integer compute() { if (n <= 1) { return n; } Fibonacci f1 = new Fibonacci(n - 1); f1.fork(); Fibonacci f2 = new Fibonacci(n - 2); return f2.compute() + f1.join(); } }
小结
- 本课学习了 Java 的并发编程,包括线程创建、线程同步和线程通信。
- 介绍了高级集合框架中的并发集合和阻塞队列。
- 探讨了 CompletableFuture 用于异步编程。
- 学习了 Fork/Join 框架,用于并行执行任务。