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