Object类wait及notify方法原理实例解析

2025-05-29 0 43

Object类中的waitnotify方法(生产者和消费者模式)  不是通过线程调用

  • 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();

}

}

}

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

原文链接:https://www.cnblogs.com/llcy/p/13468480.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Object类wait及notify方法原理实例解析 https://www.kuaiidc.com/118486.html

相关文章

发表评论
暂无评论