Object類中的wait和notify方法(生產者和消費者模式) 不是通過線程調用
- wait(): 讓正在當前對象上活動的線程進入等待狀態,無期限等待,直到被喚醒為止
- notify(): 讓正在當前對象上等待的線程喚醒
- notifyAll(): 喚醒當前對象上處于等待的所有線程
生產者和消費者模式 生產線程和消費線程達到均衡
wait方法和notify方法建立在synchronized線程同步的基礎之上
- wait方法: 釋放當前對象占有的鎖
- notify方法: 通知,不會釋放鎖
實現生產者和消費者模式 倉庫容量為10
代碼如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
import java.util.ArrayList; public class Test_14 { public static void main(String[] args) { ArrayList list = new ArrayList(); Thread t1 = new Thread( new ProducerThread(list)); t1.setName( "producer" ); Thread t2 = new Thread( new ConsumerThread(list)); t2.setName( "consumer" ); t1.start(); t2.start(); } } //生產者線程 class ProducerThread implements Runnable{ private ArrayList arrayList; public ProducerThread(ArrayList arrayList) { this .arrayList = arrayList; } @Override public void run() { while ( true ) { synchronized (arrayList) { if (arrayList.size() > 9 ){ try { arrayList.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } try { Thread.sleep( 1000 ); } catch (InterruptedException e) { e.printStackTrace(); } arrayList.add( new Object()); System.out.println(Thread.currentThread().getName() + "---> 生產" + "---庫存" + arrayList.size()); arrayList.notify(); } } } } //消費者線程 class ConsumerThread implements Runnable{ private ArrayList arrayList; public ConsumerThread(ArrayList arrayList) { this .arrayList = arrayList; } @Override public void run() { while ( true ){ synchronized (arrayList){ if (arrayList.size() < 9 ){ try { arrayList.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } try { Thread.sleep( 1000 ); } catch (InterruptedException e) { e.printStackTrace(); } arrayList.remove( 0 ); System.out.println(Thread.currentThread().getName() + "---> 消費" + "---庫存" + arrayList.size()); arrayList.notify(); } } } } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.cnblogs.com/llcy/p/13468480.html