线程同步困惑:Java多线程实例解析
在Java多线程编程中,线程同步主要是通过控制多个线程对共享资源的访问顺序,以防止数据竞争和不一致。以下是一个基本的Java多线程实例解析:
类定义:
public class ThreadSyncExample {
private int count = 0;
// 创建两个共享变量的副本
private int副本Count = 0;
// 同步方法,使用synchronized关键字
public synchronized void increment() {
count++;
System.out.println("Increment thread " + Thread.currentThread().getName() + ": " + count);
}
// 同步方法,使用synchronized块
public synchronized void copyIncrement() throws InterruptedException {
while (副本Count == 0) { // 确保副本已创建并初始化
System.out.println("Waiting for increment thread to create replica: " + Thread.currentThread().getName());
sleep(100); // 暂停,以避免多个线程同时执行
}
increment(); // 在副本已准备好的情况下进行复制和增操作
System.out.println("Increment thread after copy: " + Thread.currentThread().getName() + ": " + count);
}
}
运行示例:
public class Main {
public static void main(String[] args) {
ThreadSyncExample example = new ThreadSyncExample();
// 创建两个线程,执行同步操作
Thread thread1 = new Thread(() -> {
try {
example.copyIncrement(); // 执行复制增操作
} catch (InterruptedException e) {
e.printStackTrace();
}
}));
Thread thread2 = new Thread(() -> {
try {
example.increment(); // 执行常规增操作
} catch (Exception e) {
e.printStackTrace();
}
}));
// 启动线程
thread1.start();
thread2.start();
// 等待所有线程结束
thread1.join();
thread2.join();
System.out.println("Final count: " + example.count);
}
}
这个例子展示了Java多线程同步的两种方法:使用synchronized
关键字修饰的方法和使用synchronized
块的方法。
还没有评论,来说两句吧...