如何在Java中实现同步:面试问题及解决方法
在Java中实现同步主要依赖于两个重要的特性:互斥性和条件变量。
- 互斥锁(Synchronized):
这是最基础的同步机制。当一个线程进入synchronized代码块时,会获取到当前对象的锁,其他线程必须等到这个锁被释放才能执行。
public class Counter {
private int count;
public synchronized void increment() {
count++;
}
public synchronized int decrement() {
if (count > 0) {
count--;
return count;
} else {
throw new IllegalArgumentException("Counter is already at zero!");
}
}
// getter for count
}
- 条件变量(Condition):
当一个线程等待特定条件满足时,可以使用条件变量。通常与synchronized
一起使用。
public class SleepyThread {
private final Condition condition;
private boolean ready;
public SleepyThread(Condition condition) {
this.condition = condition;
}
// method to wait until ready
public void awaitReady() throws InterruptedException {
synchronized (condition) {
while (!ready) {
condition.await();
}
}
}
// method to signal when ready
public void signalReady() {
synchronized (condition) {
ready = true;
condition.signalAll(); // signal all waiting threads
}
}
// usage example
public static void main(String[] args) {
Condition condition = new Condition();
SleepyThread thread1 = new SleepyThread(condition);
SleepyThread thread2 = new SleepyThread(condition);
thread1.awaitReady();
thread2.signalReady();
thread1印状态("thread1 ready" + thread1的状态());
thread2印状态("thread2 ready" + thread2的状态());
// 按任意键退出
System.in.read();
}
}
这里,Condition
是java.util.concurrent.locks.Condition
的子类。awaitReady()
方法会使得线程进入等待条件满足的状态,而signalReady()
方法则用于通知线程条件已经满足。
在面试中,理解同步机制并能够运用到实际代码中是面试的重点之一。
还没有评论,来说两句吧...