并发挑战:Java多线程环境下同步与互斥问题实例
在Java多线程环境中,同步和互斥是两个常见的并发控制问题。
例子1:互斥锁(Synchronized)
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
notifyAll(); // 唤醒所有等待的线程
}
public synchronized void decrement() {
count--;
if (count == 0) {
notifyAll(); // 唤醒所有等待的线程
}
}
public int getCount() {
return count;
}
}
在这个例子中,increment
和decrement
方法被声明为synchronized
。这使得在同一时间只有一个线程能够访问这些方法,从而实现了互斥。
例子2:同步块(Synchronized Block)
public class MutexExample {
private Object lock = new Object();
public void criticalSection() {
synchronized (lock) { // 同步块
// 这里是线程安全的代码
}
}
public static void main(String[] args) {
MutexExample example = new MutexExample();
Thread thread1 = new Thread(() -> {
example.criticalSection(); // 访问同步代码
}));
Thread thread2 = new Thread(() -> {
example.criticalSection(); // 访问同步代码
}));
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
在这个例子中,criticalSection
方法被设计为一个同步块。当多个线程同时访问这个同步块时,只有一个线程能够执行里面的代码,实现了互斥和同步。
这两种方式都是Java中用来解决并发问题的重要工具。
还没有评论,来说两句吧...