在Java中,有多種方法可以實現(xiàn)多線程任務(wù)的同步執(zhí)行。以下是一些常用的方法:
public synchronized void syncMethod() {
// 同步執(zhí)行的代碼
}
public void anotherMethod() {
synchronized (this) {
// 同步執(zhí)行的代碼
}
}
import java.util.concurrent.locks.ReentrantLock;
public class MyClass {
private final ReentrantLock lock = new ReentrantLock();
public void syncMethod() {
lock.lock();
try {
// 同步執(zhí)行的代碼
} finally {
lock.unlock();
}
}
}
import java.util.concurrent.CountDownLatch;
public class MyClass {
private final CountDownLatch latch = new CountDownLatch(1);
public void syncMethod() {
// 執(zhí)行同步任務(wù)的代碼
latch.countDown(); // 減少計數(shù)器
}
public void anotherMethod() throws InterruptedException {
latch.await(); // 等待計數(shù)器變?yōu)?
// 同步執(zhí)行的代碼
}
}
import java.util.concurrent.CyclicBarrier;
public class MyClass {
private final CyclicBarrier barrier = new CyclicBarrier(2);
public void syncMethod() {
try {
barrier.await(); // 等待其他線程
// 同步執(zhí)行的代碼
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
public void anotherMethod() {
try {
barrier.await(); // 等待其他線程
// 同步執(zhí)行的代碼
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
}
import java.util.concurrent.Semaphore;
public class MyClass {
private final Semaphore semaphore = new Semaphore(1);
public void syncMethod() {
try {
semaphore.acquire(); // 獲取許可
// 同步執(zhí)行的代碼
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release(); // 釋放許可
}
}
}
根據(jù)具體的需求和場景,可以選擇合適的方法來實現(xiàn)Java多線程任務(wù)的同步執(zhí)行。