多线程同步:Java中的互斥锁与条件变量实例

原创 小灰灰 2024-09-17 12:36 168阅读 0赞

在Java中,多线程同步主要通过两种机制实现:互斥锁和条件变量。

  1. 互斥锁(Mutex)

互斥锁是一种独占资源的工具。当一个线程获得一个互斥锁后,其他线程必须等待该锁被释放才能获取。

实例:

  1. public class MutexExample {
  2. private final Object lock = new Object();
  3. public void thread1() {
  4. synchronized (lock) {
  5. System.out.println("Thread 1: Acquiring lock...");
  6. try {
  7. Thread.sleep(2000); // Simulate some work
  8. } catch (InterruptedException e) {
  9. e.printStackTrace();
  10. }
  11. System.out.println("Thread 1: Lock released, waiting...");
  12. }
  13. }
  14. public void thread2() {
  15. synchronized (lock) {
  16. System.out.println("Thread 2: Acquiring lock...");
  17. try {
  18. Thread.sleep(500); // Simulate shorter work
  19. } catch (InterruptedException e) {
  20. e.printStackTrace();
  21. }
  22. System.out.println("Thread 2: Lock released, thread continues...");
  23. }
  24. }
  25. public static void main(String[] args) {
  26. MutexExample example = new MutexExample();
  27. Thread thread1 = new Thread(example::thread1));
  28. Thread thread2 = new Thread(example::thread2));
  29. thread1.start(); // Start the first thread
  30. thread2.start(); // Start the second thread
  31. try {
  32. thread1.join(); // Wait for thread 1 to finish
  33. thread2.join(); // Wait for thread 2 to finish
  34. } catch (InterruptedException e) {
  35. e.printStackTrace();
  36. }
  37. System.out.println("Both threads finished.");
  38. }
  39. }

在上述代码中,MutexExample类包含一个互斥锁lock。两个线程thread1thread2分别对锁进行操作。

当一个线程获得了锁后,其他线程必须等待锁被释放才能获得。这样就实现了多线程的同步控制。

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

发表评论

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

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

相关阅读