新手常犯:Java多线程并发编程错误实例
在Java多线程并发编程中,新手可能会遇到各种错误。以下是一些常见的错误实例:
未初始化的静态变量:
// 错误:静态变量未初始化
static int sharedVariable = 0;
// 正确:使用ThreadLocal存储局部变量
ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
死锁:
// 错误:线程1等待线程2释放资源
class LockResource {
private Object lock;
public LockResource() {
this.lock = new Object();
}
public synchronized void acquireLock() throws InterruptedException {
while (lock != null) {
wait(lock);
}
lock = new Object();
}
public synchronized void releaseLock() {
if (lock != null) {
lock = null;
notifyAll();
}
}
}
class WorkerThread extends Thread {
private LockResource resource;
public WorkerThread(LockResource resource) {
this.resource = resource;
start();
}
@Override
public void run() {
try {
resource.acquireLock(); // 正确:先获取锁,再执行任务
// 任务示例
Thread.sleep(2000); // 模拟耗时操作
resource.releaseLock(); // 正确:释放锁后通知其他线程
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Main {
public static void main(String[] args) {
LockResource resource = new LockResource();
WorkerThread worker1 = new WorkerThread(resource);
WorkerThread worker2 = new WorkerThread(resource);
worker1.start(); // 启动线程
worker2.start(); // 同理
try {
worker1.join(); // 等待worker1完成任务
worker2.join(); // 同理,等待worker2完成任务
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
共享数据未同步:
class Counter {
private int count;
public Counter() {
this.count = 0;
}
// 错误:返回值为引用,但没有同步更新count
public synchronized int incrementCounter() {
return ++count; // 错误:直接操作count,未同步
}
public synchronized int decrementCounter() {
return --count; // 同理
}
public synchronized int getCount() {
return count;
}
}
class WorkerThread extends Thread {
private Counter counter;
public WorkerThread(Counter counter) {
this.counter = counter;
start();
}
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
// 在这里操作counter,模拟耗时操作
counter.incrementCounter(); // 错误:未同步更新count
// 模拟耗时操作
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 正确示例:使用CountDownLatch同步更新counter
counter.countDown(); // 系统会等待countdown信号到达,然后更新count为0
System.out.println("WorkerThread done." + counter.getCount()); // 输出: WorkerThread done. 0
}
}
class Main {
public static void main(String[] args) {
Counter counter = new Counter();
WorkerThread worker1 = new WorkerThread(counter);
WorkerThread worker2 = new WorkerThread(counter);
worker1.start(); // 启动线程
worker2.start(); // 同理
try {
worker1.join(); // 等待worker1完成任务
worker2.join(); // 同理,等待worker2完成任务
// 正确示例:检查counter的值,确保更新同步
if (counter.getCount() != 0) {
System.out.println("Counter value not updated correctly. Counter count: " + counter.getCount());
throw new RuntimeException("Counter synchronization error.");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Main done.");
}
}
请根据你的实际需求,修改上述代码以避免错误。
还没有评论,来说两句吧...