理解和解决Java多线程并发问题实例
Java的多线程并发问题主要涉及到线程间的同步、互斥,以及资源的竞争等问题。以下是一些实例:
线程同步问题:
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
notifyAll(); // 唤醒等待的线程
}
public synchronized int decrement() {
if (count > 0) {
count--;
notifyAll();
return count; // 返回减少后的计数
} else {
throw new IllegalArgumentException("Counter is already at zero!"); // 如果计数为零,抛出异常
}
}
}
线程竞争问题:
class LimitedResource {
private int availableResources = 10; // 先定义资源数量
public synchronized void requestResource() throws InterruptedException {
while (availableResources <= 0) { // 如果资源已耗尽,进入等待状态
wait();
if (Thread.currentThread().isInterrupted()) { // 检查是否被中断
throw new InterruptedException("Resource request interrupted by system!"); // 若中断,则抛出InterruptedException
}
}
availableResources--; // 请求一个资源
notifyAll(); // 唤醒等待的线程
}
}
通过以上实例,你可以理解Java中多线程并发问题及其解决方法。
还没有评论,来说两句吧...