理解和解决Java多线程同步问题的示例

原创 Love The Way You Lie 2024-12-01 23:57 102阅读 0赞

在Java中,多线程同步主要是通过锁(Lock)机制来实现的。常用的锁包括 synchronized 关键字、ReentrantLock 等。

以下是一个使用synchronized关键字和打印线程名称来同步两个线程的简单示例:

  1. public class SynchronizedExample {
  2. private int count = 0;
  3. public void increment() {
  4. synchronized (this) { // 同步块,锁定当前对象
  5. count++;
  6. System.out.println("Thread " + Thread.currentThread().getName() + " incremented count to " + count);
  7. }
  8. }
  9. public static void main(String[] args) {
  10. SynchronizedExample example = new SynchronizedExample();
  11. Thread thread1 = new Thread(() -> example.increment()));
  12. Thread thread2 = new Thread(() -> example.increment()));
  13. thread1.start(); // 启动线程1
  14. thread2.start(); // 启动线程2
  15. // 等待线程结束
  16. thread1.join();
  17. thread2.join();
  18. System.out.println("Final count: " + example.count)); // 验证最终计数是否正确
  19. }
  20. }

在上述示例中,两个线程(thread1thread2)同时调用 increment() 方法。由于同步块的存在,任何时刻只有一个线程可以执行同步代码,从而保证了正确的计数结果。

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

发表评论

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

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

相关阅读