理解并解决Java多线程并发问题实例
在Java中,多线程并发问题主要体现在共享资源的访问、同步机制的应用以及竞态条件等。
以下是一个具体的实例来理解这些问题:
共享资源访问:
```java
class Counter {
int count;synchronized void increment() {
count++;
notifyAll(); // 通知所有等待的线程
}
synchronized void decrement() {
count--;
if (count == 0) { // 如果计数为0,进入休眠状态
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// 多个线程同时访问共享资源
class WorkerThread extends Thread {
private Counter counter;
public WorkerThread(Counter counter) {
this.counter = counter;
}
@Override
public void run() {
while (true) { // 无限循环,模拟工作状态
try {
counter.increment(); // 增加计数
System.out.println("Work done by thread " + this.getName()); // 打印工作完成信息
Thread.sleep(100); // 等待一段时间再执行下一条语句
} catch (InterruptedException e) {
System.out.println(this.getName() + ": Interrupted while sleeping!"); // 当线程被中断时,打印日志
e.printStackTrace();
}
}
}
}
public class Main {
public static void main(String[] args) {
Counter counter = new Counter();
// 创建并启动多个工作线程
for (int i = 0; i < 5; i++) {
WorkerThread workerThread = new WorkerThread(counter);
workerThread.setName("Thread " + i); // 设置线程名称
workerThread.start(); // 启动线程
}
// 确保所有工作线程完成其任务后,主线程再执行其他操作
System.out.println("All worker threads completed their tasks."); // 打印日志,表示所有工作线程已经完成它们的任务
}
}
```
在这个例子中,我们创建了一个共享的Counter对象。多个线程(WorkerThread)同时访问这个Counter,模拟多线程并发情况。
通过设置适当的同步机制(如synchronized关键字),我们可以避免竞态条件导致的问题,并确保所有操作按照预期进行。
还没有评论,来说两句吧...