多线程同步问题:Java中的wait/notify用法示例

原创 谁践踏了优雅 2024-12-04 19:00 114阅读 0赞

在Java中,wait和notify是用于线程同步的两个关键方法。当一个线程需要等待某个条件满足时,会调用wait();而另一个线程在条件满足后,会调用notify()或notifyAll()。

以下是一个简单的示例,展示了wait/notify的使用:

  1. class Counter {
  2. private int count = 0;
  3. public synchronized void increment() {
  4. count++;
  5. notifyAll(); // 当count大于0时唤醒所有等待的线程
  6. }
  7. public synchronized void decrement() {
  8. if (count > 0) {
  9. count--;
  10. if (count == 0) { // 如果count为0,表示计数器为空
  11. notifyAll(); // 唤醒所有等待的线程
  12. }
  13. }
  14. }
  15. }
  16. public class Main {
  17. public static void main(String[] args) {
  18. Counter counter = new Counter();
  19. // 创建两个线程并开始执行
  20. Thread thread1 = new Thread(() -> {
  21. while (true) { // 无限循环,直到被唤醒
  22. try {
  23. // 等待计数器不为空(即counter.increment()已经调用)
  24. if (!counter.decrement()) {
  25. break; // 当count为0时跳出循环
  26. }
  27. } catch (InterruptedException e) {
  28. e.printStackTrace();
  29. }
  30. }
  31. }));
  32. Thread thread2 = new Thread(() -> {
  33. while (true) { // 无限循环,直到被唤醒
  34. try {
  35. // 等待计数器不为空(即counter.increment()已经调用)
  36. if (!counter.increment()) {
  37. break; // 当count大于0时跳出循环
  38. }
  39. } catch (InterruptedException e) {
  40. e.printStackTrace();
  41. }
  42. }
  43. }));
  44. thread1.start(); // 启动thread1
  45. thread2.start(); // 启动thread2
  46. // 当计数器为空(即counter.increment()未调用)时,会唤醒所有等待的线程
  47. // 这里通过检查count是否为0来实现这个逻辑
  48. }
  49. }

在这个示例中,我们创建了一个Counter类,用于维护一个计数器。然后我们创建了两个线程thread1和thread2,它们在无限循环中等待被唤醒。最后当计数器为空时,会唤醒所有等待的线程。

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

发表评论

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

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

相关阅读