在 Java 中,可以使用多种并发控制方法来管理多线程程序的执行。以下是一些常用的并发控制方法:
public synchronized void synchronizedMethod() {
// 同步代码
}
public void methodWithSynchronizedBlock() {
synchronized (this) {
// 同步代码
}
}
import java.util.concurrent.locks.ReentrantLock;
public class MyRunnable implements Runnable {
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
lock.lock();
try {
// 同步代码
} finally {
lock.unlock();
}
}
}
import java.util.concurrent.Semaphore;
public class MyRunnable implements Runnable {
private final Semaphore semaphore = new Semaphore(3); // 允许最多 3 个线程同时访问
@Override
public void run() {
try {
semaphore.acquire();
// 同步代码
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
}
}
import java.util.concurrent.CountDownLatch;
public class MyRunnable implements Runnable {
private final CountDownLatch latch = new CountDownLatch(3); // 等待 3 个线程完成
@Override
public void run() {
try {
// 执行任务
latch.countDown(); // 减少计数器
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
try {
latch.await(); // 等待计数器归零
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
import java.util.concurrent.CyclicBarrier;
public class MyRunnable implements Runnable {
private final CyclicBarrier barrier = new CyclicBarrier(3); // 等待 3 个线程达到屏障点
@Override
public void run() {
try {
// 执行任务
barrier.await(); // 等待所有线程达到屏障点
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MyRunnable implements Runnable {
private static final ExecutorService executorService = Executors.newFixedThreadPool(3); // 创建一个包含 3 个线程的线程池
@Override
public void run() {
executorService.submit(this); // 将任务提交给线程池执行
}
}
这些并发控制方法可以根据具体需求进行组合使用,以实现更复杂的线程同步和协作。