Java Gossip: wait()、notify()
wait()、notify() notifyAll() Object , ( Java Object),wait()、notify() notifyAll() "final", , Runnable 。
wait() , wait() , “ ”(Wait set) , , , ; ,wait() , , , 0 , , (interrupt) (notify) 。
notify() , “ ” , , ; notifyAll(), “ ” , 。
, wait() , , , , , ( 1 ), ( ) 。
wait()、notify() notifyAll() , (Producer) (Consumer) , , , , , (wait), (notify) , , (wait), (notify) 。
: int , , 。
, :
Producer.java
package onlyfun.caterpillar; public class Producer implements Runnable { private Clerk clerk; public Producer(Clerk clerk) { this.clerk = clerk; } public void run() { System.out.println( " ......"); // 1 10 for(int product = 1; product <= 10; product++) { try { // Thread.sleep((int) (Math.random() * 3000)); } catch(InterruptedException e) { e.printStackTrace(); } // clerk.setProduct(product); } } }
:
Consumer.java
package onlyfun.caterpillar; public class Consumer implements Runnable { private Clerk clerk; public Consumer(Clerk clerk) { this.clerk = clerk; } public void run() { System.out.println( " ......"); // 10 for(int i = 1; i <= 10; i++) { try { // Thread.sleep((int) (Math.random() * 3000)); } catch(InterruptedException e) { e.printStackTrace(); } // clerk.getProduct(); } } }
, , 。
Clerk.java
package onlyfun.caterpillar; public class Clerk { // -1 private int product = -1; // public synchronized void setProduct(int product) { if(this.product != -1) { try { // , ! wait(); } catch(InterruptedException e) { e.printStackTrace(); } } this.product = product; System.out.printf(" (%d)%n", this.product); // notify(); } // public synchronized int getProduct() { if(this.product == -1) { try { // , ! wait(); } catch(InterruptedException e) { e.printStackTrace(); } } int p = this.product; System.out.printf( " (%d)%n", this.product); this.product = -1; // notify(); return p; } }
:
WaitNotifyDemo.java
package onlyfun.caterpillar; public class WaitNotifyDemo { public static void main(String[] args) { Clerk clerk = new Clerk(); Thread producerThread = new Thread( new Producer(clerk)); Thread consumerThread = new Thread( new Consumer(clerk)); producerThread.start(); consumerThread.start(); }}
:
......
......
(1)
(1)
(2)
(2)
(3)
(3)
(4)
(4)
(5)
(5)
(6)
(6)
(7)
(7)
(8)
(8)
(9)
(9)
(10)
(10)
10 , 10 , , , 。
, , InterruptedException ,interrupt() 。
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.