Java 中的线程同步和互斥机制可以防止多个线程同时访问共享资源导致数据不一致的问题。Java 中的线程同步和互斥机制有多种实现方式,包括 synchronized 关键字、Lock 接口、Semaphore 类、Condition 接口等。
synchronized 关键字可以保证同步访问共享资源,其用法有两种:
在方法前加上 synchronized 关键字,保证同一时刻只有一个线程能够执行该方法。
public synchronized void method() {
// 同步代码块
}
在代码块前加上 synchronized 关键字,保证同一时刻只有一个线程能够执行该代码块。
public void method() {
synchronized (this) {
// 同步代码块
}
}
Lock 接口提供了比 synchronized 更为灵活的锁机制。Lock 接口有多个实现类,其中最常用的是 ReentrantLock 类。ReentrantLock 类实现了 Lock 接口,使用方式如下:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class MyRunnable implements Runnable {
private Lock lock = new ReentrantLock(); // 创建可重入锁
@Override
public void run() {
lock.lock(); // 获取锁
try {
// 同步代码块
} finally {
lock.unlock(); // 释放锁
}
}
}
在该例子中,我们使用 ReentrantLock 类创建了一个可重入锁,并在 run() 方法中使用了 lock() 方法获取锁,使用了 unlock() 方法释放锁。
Semaphore 类可以控制并发线程的数量,其用法如下:
import java.util.concurrent.Semaphore;
public class MyRunnable implements Runnable {
private Semaphore semaphore = new Semaphore(2); // 创建 Semaphore 对象,限制线程数量为 2
@Override
public void run() {
try {
semaphore.acquire(); // 获取许可证
// 同步代码块
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release(); // 释放许可证
}
}
}
在该例子中,我们创建了一个 Semaphore 对象,限制线程数量为 2,然后在 run() 方法中使用了 acquire() 方法获取许可证,使用了 release() 方法释放许可证。
Condition 接口可以实现线程之间的通信,其用法如下:
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class MyRunnable implements Runnable {
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition(); // 创建条件变量
@Override
public void run() {
lock.lock();
try {
while (true) {
condition.await(); // 等待信号
// 处理信号
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void signal() {
lock.lock();
try {
condition.signal(); // 发送信号
} finally {
lock.unlock();
}
}
}
在该例子中,我们使用 Lock 和 Condition 接口实现了线程之间的通信。在 run() 方法中,我们使用了 await() 方法等待信号,使用了 signal() 方法发送信号。
线程池是一种重用线程的机制,可以避免线程的频繁创建和销毁,提高了线程的利用率。Java 中的线程池是通过 Executor 框架实现的,包括 Executor、ExecutorService 和 ThreadPoolExecutor 三个类。
Executor 是一个接口,只定义了一个 execute(Runnable command) 方法,用于执行 Runnable 对象。
import java.util.concurrent.Executor;
public class MyRunnable implements Runnable {
@Override
public void run() {
// 线程执行的代码
}
}
public class Test {
public static void main(String[] args) {
Executor executor = Executors.newSingleThreadExecutor(); // 创建 Executor 对象
executor.execute(new MyRunnable()); // 执行线程
}
}
在该例子中,我们使用 Executors 工厂类创建了一个单线程的 Executor 对象,然后使用 execute() 方法执行了一个 MyRunnable 对象。
ExecutorService 接口继承自 Executor 接口,提供了更多的方法,如提交任务、关闭线程池等。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MyRunnable implements Runnable {
@Override
public void run() {
// 线程执行的代码
}
}
public class Test {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(2); // 创建 ExecutorService 对象
executorService.execute(new MyRunnable()); // 执行线程
executorService.shutdown(); // 关闭线程池
}
}
在该例子中,我们使用 Executors 工厂类创建了一个固定大小为 2 的线程池,然后使用 execute() 方法执行了一个 MyRunnable 对象,最后使用 shutdown() 方法关闭了线程池。
ThreadPoolExecutor 类是 ExecutorService 接口的默认实现,提供了更为灵活的线程池管理。
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class MyRunnable implements Runnable {
@Override
public void run() {
// 线程执行的代码
}
}
public class Test {
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 4, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); // 创建 ThreadPoolExecutor 对象
threadPoolExecutor.execute(new MyRunnable()); // 执行线程
threadPoolExecutor.shutdown(); // 关闭线程池
}
}
在该例子中,我们使用 ThreadPoolExecutor 类创建了一个大小为 2-4 的线程池,使用 execute() 方法执行了一个 MyRunnable 对象,最后使用 shutdown() 方法关闭了线程池。