如何解决Java多线程同步问题?实例演示
在Java中,多线程同步主要是通过synchronized关键字、wait/notify机制和Lock接口来实现的。
synchronized
关键字:
在单个 synchronized 块上,同一时间只能有一个线程执行该块。例如:
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
public class ThreadSyncExample {
public static void main(String[] args) {
Counter counter = new Counter();
// 创建两个线程
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
counter.increment();
try {
// 线程休眠,模拟其他线程操作
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}));
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
counter.getCount(); // 每次调用都可能阻塞,直到计数器变化
try {
// 线程休眠,模拟其他线程操作
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}));
// 启动线程
thread1.start();
thread2.start();
// 等待所有线程结束
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
在这个例子中,我们创建了一个Counter类,它的increment方法用于增加计数器的值,而getCount方法每次调用都可能阻塞。
两个线程分别调用这两个方法,并在操作之间插入休眠,模拟其他线程的交互。最后,我们等待所有线程结束。
还没有评论,来说两句吧...