要将多个线程同步到公共点,可以使用线程同步机制。在Java中,可以使用以下方法:
synchronized
关键字:public class SynchronizedExample {
public void synchronizedMethod() {
synchronized (this) {
// 同步代码块
}
}
}
CountDownLatch
:import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
public void countDownLatchMethod() throws InterruptedException {
int threadCount = 10;
CountDownLatch countDownLatch = new CountDownLatch(threadCount);
for (int i = 0; i< threadCount; i++) {
new Thread(() -> {
// 执行线程任务
countDownLatch.countDown();
}).start();
}
countDownLatch.await(); // 等待所有线程执行完毕
// 继续执行主线程任务
}
}
CyclicBarrier
:import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierExample {
public void cyclicBarrierMethod() throws InterruptedException {
int threadCount = 10;
CyclicBarrier cyclicBarrier = new CyclicBarrier(threadCount, () -> {
// 所有线程到达屏障后执行的任务
});
for (int i = 0; i< threadCount; i++) {
new Thread(() -> {
// 执行线程任务
try {
cyclicBarrier.await(); // 等待所有线程到达屏障
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
}
Semaphore
:import java.util.concurrent.Semaphore;
public class SemaphoreExample {
public void semaphoreMethod() throws InterruptedException {
int threadCount = 10;
Semaphore semaphore = new Semaphore(threadCount);
for (int i = 0; i< threadCount; i++) {
new Thread(() -> {
try {
semaphore.acquire(); // 获取许可
// 执行线程任务
semaphore.release(); // 释放许可
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}
}
以上方法都可以实现线程同步,具体使用哪种方法取决于具体的需求和场景。
领取专属 10元无门槛券
手把手带您无忧上云