在 Java 中,多线程的实现方法和同步机制有多种选择。下面分别介绍几种常见的多线程实现方法和同步方法。
多线程实现方法
1. 继承 Thread
类:
- 创建一个新类继承
Thread
类,并重写其run
方法。 - 创建该类的实例并调用
start
方法启动新线程。class MyThread extends Thread { public void run() { System.out.println("Thread is running."); } } public class Main { public static void main(String[] args) { MyThread t1 = new MyThread(); t1.start(); } }
2. 实现 Runnable
接口:
- 创建一个实现
Runnable
接口的类,并实现其run
方法。 - 将该类的实例传递给
Thread
对象,并调用start
方法启动新线程。class MyRunnable implements Runnable { public void run() { System.out.println("Thread is running."); } } public class Main { public static void main(String[] args) { Thread t1 = new Thread(new MyRunnable()); t1.start(); } }
3. 使用 Callable
和 Future
:
- 创建一个实现
Callable
接口的类,并实现其call
方法,该方法可以返回值。 - 使用
ExecutorService
提交任务,并通过Future
获取返回值或处理异常。import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; class MyCallable implements Callable<String> { public String call() throws Exception { return "Callable Result"; } } public class Main { public static void main(String[] args) throws Exception { FutureTask<String> futureTask = new FutureTask<>(new MyCallable()); Thread t1 = new Thread(futureTask); t1.start(); System.out.println(futureTask.get()); } }
4. 使用线程池(Executors):
- 使用
Executors
提供的各种线程池来管理线程。import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Main { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(5); for (int i = 0; i < 10; i++) { executor.execute(new Runnable() { public void run() { System.out.println("Thread is running."); } }); } executor.shutdown(); } }
同步实现方法
1. 同步代码方法/块(synchronized method/block):
- 使用
synchronized
关键字同步特定的代码块,以一个对象作为锁。public class Main { private int count = 0; public synchronized void increment() { count++; } public static void main(String[] args) throws InterruptedException { Main obj = new Main(); Thread t1 = new Thread(() -> { for (int i = 0; i < 1000; i++) { obj.increment(); } }); Thread t2 = new Thread(() -> { for (int i = 0; i < 1000; i++) { obj.increment(); } }); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("Count: " + obj.count); } }
2. 显式锁(ReentrantLock):
- 适用于需要更加灵活的锁定机制,如非块结构的锁定、定时锁定等。
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Main { private int count = 0; private final Lock lock = new ReentrantLock(); public void increment() { lock.lock(); try { count++; } finally { lock.unlock(); } } public static void main(String[] args) throws InterruptedException { Main obj = new Main(); Thread t1 = new Thread(() -> { for (int i = 0; i < 1000; i++) { obj.increment(); } }); Thread t2 = new Thread(() -> { for (int i = 0; i < 1000; i++) { obj.increment(); } }); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("Count: " + obj.count); } }
3. 读写锁(ReentrantReadWriteLock):
- 使用
java.util.concurrent.locks.ReentrantReadWriteLock
类实现读写锁,允许多个读线程,但写线程是互斥的。 - 读锁:允许多个线程同时获取,只要没有任何线程持有写锁。
- 写锁:独占锁,只能被一个线程持有,并且当写锁被持有时,所有的读锁和其他写锁的请求都会被阻塞,直到写锁被释放。
import java.util.concurrent.locks.ReentrantReadWriteLock; public class ReadWriteLockExample { private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(); private final ReentrantReadWriteLock.ReadLock readLock = rwLock.readLock(); private final ReentrantReadWriteLock.WriteLock writeLock = rwLock.writeLock(); private int sharedData = 0; // 读操作 public void readData() { readLock.lock(); try { // 允许多个线程同时读取 sharedData System.out.println("Reading data: " + sharedData); } finally { readLock.unlock(); } } // 写操作 public void writeData(int data) { writeLock.lock(); try { // 只有一个线程可以写入 sharedData sharedData = data; System.out.println("Writing data: " + sharedData); } finally { writeLock.unlock(); } } }
4. 原子类(Atomic)
- 适用于需要原子性操作的场景,如递增、递减等。
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
private AtomicInteger count = new AtomicInteger(0);
public void increment() {
count.incrementAndGet();
}
public static void main(String[] args) throws InterruptedException {
Main obj = new Main();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
obj.increment();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
obj.increment();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Count: " + obj.count);
}
}
5. 信号量(Semaphore):
- 使用场景:限制对某种资源的访问数量,控制并发线程的数量。适合需要限流或控制资源访问的场景。
- 示例:数据库连接池,限制同时访问数据库的线程数。
- 代码示例:
import java.util.concurrent.Semaphore; public class MyClass { private final Semaphore semaphore = new Semaphore(1); public void method() { try { semaphore.acquire(); // 受限访问的代码 } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { semaphore.release(); } } }
6. 保证可见性(volatile)
- 适用于确保变量的可见性,不适用于复合操作(如递增)。
public class Main {
private volatile boolean running = true;
public void stop() {
running = false;
}
public static void main(String[] args) {
Main obj = new Main();
Thread t1 = new Thread(() -> {
while (obj.running) {
// Do some work
}
System.out.println("Thread stopped.");
});
t1.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
obj.stop();
}
}
总结
-
多线程实现方法:
- 继承
Thread
类 - 实现
Runnable
接口 - 使用
Callable
和Future
- 使用线程池(
Executors
)
- 继承
-
同步实现方法:
- 同步代码块(
synchronized block/method
) - 显式锁(
ReentrantLock
) - 读写锁(
ReentrantReadWriteLock
) - 原子类(
Atomic
) - 信号量(
Semaphore
) - 保证可见性(
volatile
)
- 同步代码块(
选择合适的方法取决于具体的应用场景和需求。