import java.util.concurrent.locks.ReentrantLock;
public class SyncExample {
private static ReentrantLock lock = new ReentrantLock();
private static void doSomething() {
lock.lock();
try {
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
Thread thread1 = new Thread(SyncExample::doSomething);
Thread thread2 = new Thread(SyncExample::doSomething);
thread1.start();
thread2.start();
}
}
import java.util.concurrent.Semaphore;
public class MutexExample {
private static Semaphore semaphore = new Semaphore(1);
private static void doSomething() throws InterruptedException {
semaphore.acquire();
try {
} finally {
semaphore.release();
}
}
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
try {
MutexExample.doSomething();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread thread2 = new Thread(() -> {
try {
MutexExample.doSomething();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread1.start();
thread2.start();
}
}