Java多线程:资源竞争示例
在Java多线程中,资源竞争是一个常见的问题。简单来说,就是多个线程同时争夺有限的资源,如果没有适当的同步机制,可能会导致数据不一致或者死锁等问题。
以下是一个经典的资源共享问题示例:
class Resource {
private int count = 0;
public synchronized void acquire() {
count++;
}
public synchronized void release() {
if (count > 0) {
count--;
} else {
// This should never happen, but just in case...
throw new RuntimeException("Resource released when not acquired");
}
}
}
public class Main {
private Resource resource;
public Main() {
resource = new Resource();
}
public synchronized void acquireResource() {
resource.acquire();
}
public synchronized void releaseResource() {
resource.release();
}
public static void main(String[] args) {
Main main = new Main();
// 多线程竞争资源
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
main.acquireResource(); // 线程1尝试获取资源
try {
Thread.sleep(100); // 模拟操作耗时
} catch (InterruptedException e) {
e.printStackTrace();
}
main.releaseResource(); // 线程1释放资源
}
}));
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
main.acquireResource(); // 线程2尝试获取资源
try {
Thread.sleep(100); // 模拟操作耗时
} catch (InterruptedException e) {
e.printStackTrace();
}
main.releaseResource(); // 线程2释放资源
}
}));
thread1.start();
thread2.start();
// 主线程等待所有子线程执行完毕
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("资源释放完成!");
}
}
在这个示例中,Resource
类代表一个共享资源。两个子线程(thread1
和 thread2
)交替尝试获取和释放资源。
如果资源管理不当,可能会导致资源耗尽或者数据不一致等问题。
还没有评论,来说两句吧...