Java多线程并发问题实例解析
在Java编程中,多线程并发是一个常见的挑战。这里我们将通过几个具体的实例来解析这些并发问题。
资源竞争:
当两个或多个线程同时访问和修改一个共享资源(如变量、文件等)时,就会出现资源竞争的问题。// 示例:共享变量 count,多线程同时更新
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
notifyAll(); // 唤醒等待的线程
}
public synchronized int value() {
return count;
}
}
死锁:
当两个或多个线程在执行过程中,因争夺资源而造成的一种互相等待的现象称为死锁。// 示例:两个线程同时请求资源 A 和 B,但先获得资源 A 的线程会等待获取资源 B,从而陷入死锁
public class DeadlockExample {
private Object resourceA = new Object();
private Object resourceB = new Object();
public void thread1() {
synchronized (resourceA) {
// 先获得资源 A
System.out.println("Thread 1 acquires A");
// 等待资源 B
try {
synchronized (resourceB) {
// 确保 B 被正确获取,否则会死锁
System.out.println("Thread 1 waits for B");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
// 执行任务后释放资源 A
System.out.println("Thread 1 releases A");
// 现在可以获取资源 B
synchronized (resourceB) {
// 获取并使用资源 B
System.out.println("Thread 1 acquires B");
}
}
}
public void thread2() {
synchronized (resourceB) {
// 先获得资源 B,线程会等待
System.out.println("Thread 2 acquires B");
// 等待资源 A
try {
synchronized (resourceA) {
// Thread 2 需要等待 Thread 1 释放资源 A
System.out.println("Thread 2 waits for A");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
// 执行任务后释放资源 B
synchronized (resourceB) {
// 此时可以获取并使用资源 B
System.out.println("Thread 2 releases B");
// 现在可以获取资源 A
synchronized (resourceA) {
// 获取并使用资源 A
System.out.println("Thread 2 acquires A");
}
}
}
}
public static void main(String[] args) {
DeadlockExample example = new DeadlockExample();
Thread thread1 = new Thread(example::thread1));
Thread thread2 = new Thread(example::thread2));
// 启动线程
thread1.start();
thread2.start();
// 等待所有线程完成
while (thread1.is_alive() || thread2.is_alive()) {
try {
// 休眠一会儿,防止一直阻塞
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("All threads completed.");
}
}
这个例子展示了两个线程(Thread 1 和 Thread 2)共享资源 A 和 B,从而可能导致死锁。
还没有评论,来说两句吧...