线程同步困惑:Java多线程实例解析

原创 悠悠 2024-12-01 12:15 91阅读 0赞

在Java多线程编程中,线程同步主要是通过控制多个线程对共享资源的访问顺序,以防止数据竞争和不一致。以下是一个基本的Java多线程实例解析:

  1. 类定义

    1. public class ThreadSyncExample {
    2. private int count = 0;
    3. // 创建两个共享变量的副本
    4. private int副本Count = 0;
    5. // 同步方法,使用synchronized关键字
    6. public synchronized void increment() {
    7. count++;
    8. System.out.println("Increment thread " + Thread.currentThread().getName() + ": " + count);
    9. }
    10. // 同步方法,使用synchronized块
    11. public synchronized void copyIncrement() throws InterruptedException {
    12. while (副本Count == 0) { // 确保副本已创建并初始化
    13. System.out.println("Waiting for increment thread to create replica: " + Thread.currentThread().getName());
    14. sleep(100); // 暂停,以避免多个线程同时执行
    15. }
    16. increment(); // 在副本已准备好的情况下进行复制和增操作
    17. System.out.println("Increment thread after copy: " + Thread.currentThread().getName() + ": " + count);
    18. }
    19. }
  2. 运行示例

    1. public class Main {
    2. public static void main(String[] args) {
    3. ThreadSyncExample example = new ThreadSyncExample();
    4. // 创建两个线程,执行同步操作
    5. Thread thread1 = new Thread(() -> {
    6. try {
    7. example.copyIncrement(); // 执行复制增操作
    8. } catch (InterruptedException e) {
    9. e.printStackTrace();
    10. }
    11. }));
    12. Thread thread2 = new Thread(() -> {
    13. try {
    14. example.increment(); // 执行常规增操作
    15. } catch (Exception e) {
    16. e.printStackTrace();
    17. }
    18. }));
    19. // 启动线程
    20. thread1.start();
    21. thread2.start();
    22. // 等待所有线程结束
    23. thread1.join();
    24. thread2.join();
    25. System.out.println("Final count: " + example.count);
    26. }
    27. }

这个例子展示了Java多线程同步的两种方法:使用synchronized关键字修饰的方法和使用synchronized块的方法。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,91人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java线同步问题实例

    在Java编程中,多线程同步是一个核心问题。以下通过一个实际案例来解析这个问题。 **案例:银行取款机** 假设我们有一个银行的自动取款机(ATM),它有多个取款通道供用户