java线程等待如何优雅地进行资源共享

avatar
作者
猴君
阅读量:1

在Java中,线程等待通常可以通过使用wait()和notify()方法来实现资源共享。wait()方法用于使当前线程等待并释放对象的锁,而notify()方法用于唤醒等待中的线程。下面是一个简单的示例代码来展示如何优雅地使用wait()和notify()方法进行资源共享:

public class Resource {     private int value;     private boolean isSet = false;      public synchronized void setValue(int value) {         while (isSet) {             try {                 wait();             } catch (InterruptedException e) {                 Thread.currentThread().interrupt();             }         }         this.value = value;         isSet = true;         System.out.println("Set value: " + value);         notify();     }      public synchronized int getValue() {         while (!isSet) {             try {                 wait();             } catch (InterruptedException e) {                 Thread.currentThread().interrupt();             }         }         isSet = false;         System.out.println("Get value: " + value);         notify();         return value;     }      public static void main(String[] args) {         Resource resource = new Resource();          Thread producerThread = new Thread(() -> {             for (int i = 0; i < 5; i++) {                 resource.setValue(i);             }         });          Thread consumerThread = new Thread(() -> {             for (int i = 0; i < 5; i++) {                 resource.getValue();             }         });          producerThread.start();         consumerThread.start();     } } 

在上面的示例中,Resource类代表一个共享资源,setValue()方法用于设置值,getValue()方法用于获取值。在setValue()和getValue()方法中使用了synchronized关键字来保证线程安全,并通过wait()和notify()方法来实现线程等待和唤醒。通过这种方式,可以实现线程之间的资源共享和协作。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!