深入理解 Java 并发编程中的线程、锁、同步机制、原子操作等核心知识点,对于编写高效、安全的多线程程序至关重要。下面通过代码示例详细说明这些概念。
1. 线程 (Thread)
线程是程序执行的基本单元。Java 提供了 Thread
类和 Runnable
接口来创建和管理线程。
public class ThreadExample {
public static void main(String[] args) {
// 使用 Thread 类
Thread thread1 = new Thread() {
public void run() {
System.out.println("Thread using Thread class");
}
};
// 使用 Runnable 接口
Runnable runnable = () -> System.out.println("Thread using Runnable interface");
Thread thread2 = new Thread(runnable);
thread1.start();
thread2.start();
}
}
2. 锁 (Lock)
锁用于控制多个线程对共享资源的访问。Java 提供了 ReentrantLock
类来实现显式锁。
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LockExample {
private final Lock lock = new ReentrantLock();
public void performTask() {
lock.lock();
try {
// 临界区代码
System.out.println("Lock acquired, performing task");
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
LockExample example = new LockExample();
Thread thread1 = new Thread(example::performTask);
Thread thread2 = new Thread(example::performTask);
thread1.start();
thread2.start();
}
}
3. 同步机制 (Synchronization)
同步机制通过 synchronized
关键字来确保同一时间只有一个线程执行某段代码,避免竞争条件。
public class SynchronizedExample {
private int counter = 0;
public synchronized void increment() {
counter++;
}
public static void main(String[] args) {
SynchronizedExample example = new SynchronizedExample();
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
example.increment();
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
example.increment();
}
});
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Counter: " + example.counter);
}
}
4. 原子操作 (Atomic Operations)
原子操作是不可分割的,保证在多线程环境下操作的原子性。Java 提供了 java.util.concurrent.atomic
包中的类来实现原子操作。
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicExample {
private AtomicInteger counter = new AtomicInteger(0);
public void increment() {
counter.incrementAndGet();
}
public static void main(String[] args) {
AtomicExample example = new AtomicExample();
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
example.increment();
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
example.increment();
}
});
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Counter: " + example.counter.get());
}
}
总结
以上是 Java 并发编程中的一些核心概念和实现方式:
- 线程:使用
Thread
类或Runnable
接口创建和管理线程。 - 锁:使用
ReentrantLock
实现显式锁。 - 同步机制:使用
synchronized
关键字确保同步。 - 原子操作:使用
AtomicInteger
等类进行原子操作。
通过这些示例,可以理解如何在 Java 中实现并发控制,确保线程安全。