Java多线程同步问题实例及解决方案

原创 £神魔★判官ぃ 2024-09-16 05:06 225阅读 0赞

在Java中,多线程的同步问题主要体现在以下几种情况:

  1. 互斥锁(Mutex)
    当一个线程访问资源时,其他线程必须等待。这时就需要互斥锁。
  1. import java.util.concurrent.Lock;
  2. import java.util.concurrent.Runnable;
  3. import java.util.concurrent.locks.ReentrantLock;
  4. public class MutexExample implements Runnable {
  5. private Lock lock = new ReentrantLock();
  6. @Override
  7. public void run() {
  8. try {
  9. // 为资源获取锁
  10. lock.acquire();
  11. System.out.println("Thread " + Thread.currentThread().getName() + " is accessing the resource...");
  12. // 使用完资源后释放锁
  13. lock.release();
  14. System.out.println("Thread " + Thread.currentThread().getName() + " has released the resource.");
  15. } catch (InterruptedException e) {
  16. e.printStackTrace();
  17. }
  18. }
  19. public static void main(String[] args) {
  20. MutexExample example = new MutexExample();
  21. Thread thread1 = new Thread(example, "Thread 1"));
  22. Thread thread2 = new Thread(example, "Thread 2"));
  23. thread1.start();
  24. thread2.start();
  25. // 等待所有线程完成
  26. try {
  27. thread1.join();
  28. thread2.join();
  29. } catch (InterruptedException e) {
  30. e.printStackTrace();
  31. }
  32. }
  33. }
  1. 条件变量(Condition)
    条件变量用于在多线程环境中实现基于特定条件的同步。
  1. import java.util.concurrent.locks.Condition;
  2. import java.util.concurrent.locks.Lock;
  3. import java.util.concurrent.locks.ReentrantLock;
  4. public class ConditionVariableExample implements Runnable {
  5. private Lock lock = new ReentrantLock();
  6. private Condition condition = lock.newCondition();
  7. private int count = 0;
  8. @Override
  9. public void run() {
  10. try {
  11. // 获取锁
  12. lock.acquire();
  13. // 设置条件
  14. condition.signalAll();
  15. System.out.println("Thread " + Thread.currentThread().getName() + " is waiting for a signal.");
  16. // 等待信号
  17. while (!condition.await(500, TimeUnit.MILLISECONDS)))) {
  18. System.out.println("Thread " + Thread.currentThread().getName() + " still waiting for a signal.");
  19. }
  20. System.out.println("Thread " + Thread.currentThread().getName() + " has received the signal and will continue its execution.");
  21. } catch (InterruptedException e) {
  22. e.printStackTrace();
  23. } finally {
  24. // 无论是否发生中断,都需要释放锁
  25. lock.release();
  26. }
  27. }
  28. public static void main(String[] args) {
  29. ConditionVariableExample example = new ConditionVariableExample();
  30. Thread thread1 = new Thread(example, "Thread 1"));
  31. Thread thread2 = new Thread(example, "Thread 2"));
  32. thread1.start();
  33. thread2.start();
  34. // 等待所有线程完成
  35. try {
  36. thread1.join();
  37. thread2.join();
  38. } catch (InterruptedException e) {
  39. e.printStackTrace();
  40. }
  41. }
  42. }
  1. synchronized
    synchronized关键字用于修饰代码块,确保同一时刻只有一个线程访问该部分代码。
  1. public class SynchronizedExample {
  2. private Object lock = new Object();
  3. public void doSomething() {
  4. synchronized (lock) { // 使用锁对象
  5. System.out.println("Thread " + Thread.currentThread().getName() + " is accessing the method.");
  6. try {
  7. // 这里是你要执行的代码
  8. Thread.sleep(500); // 等待500毫秒
  9. } catch (InterruptedException e) {
  10. e.printStackTrace();
  11. }
  12. }
  13. }
  14. public static void main(String[] args) {
  15. SynchronizedExample example = new SynchronizedExample();
  16. Thread thread1 = new Thread(example, "Thread 1"));
  17. Thread thread2 = new Thread(example, "Thread 2"));
  18. thread1.start();
  19. thread2.start();
  20. // 等待所有线程完成
  21. try {
  22. thread1.join();
  23. thread2.join();
  24. } catch (InterruptedException e) {
  25. e.printStackTrace();
  26. }
  27. }
  28. }

通过以上例子,你可以了解到如何在Java多线程中使用互斥锁、条件变量和synchronized块来实现同步。

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

发表评论

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

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

相关阅读