java多线程if wait_浅谈java多线程wait,notify

前言

1.因为涉及到对象锁,Wait、Notify一定要在synchronized里面进行使用。

2.Wait必须暂定当前正在执行的线程,并释放资源锁,让其他线程可以有机会运行

3.notify/notifyall: 唤醒线程

共享变量

public class ShareEntity {

private String name;

// 线程通讯标识

private Boolean flag = false;

public ShareEntity() {

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public Boolean getFlag() {

return flag;

}

public void setFlag(Boolean flag) {

this.flag = flag;

}

}

线程1(生产者)

public class CommunicationThread1 extends Thread{

private ShareEntity shareEntity;

public CommunicationThread1(ShareEntity shareEntity) {

this.shareEntity = shareEntity;

}

@Override

public void run() {

int num = 0;

while (true) {

synchronized (shareEntity) {

if (shareEntity.getFlag()) {

try {

shareEntity.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

if (num % 2 == 0)

shareEntity.setName("thread1-set-name-0");

else

shareEntity.setName("thread1-set-name-1");

num++;

shareEntity.setFlag(true);

shareEntity.notify();

}

}

}

}

线程2(消费者)

public class CommunicationThread2 extends Thread{

private ShareEntity shareEntity;

public CommunicationThread2(ShareEntity shareEntity) {

this.shareEntity = shareEntity;

}

@Override

public void run() {

while (true) {

synchronized (shareEntity) {

if (!shareEntity.getFlag()) {

try {

shareEntity.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

System.out.println(shareEntity.getName());

shareEntity.setFlag(false);

shareEntity.notify();

}

}

}

}

请求

@RequestMapping("test-communication")

public void testCommunication() {

ShareEntity shareEntity = new ShareEntity();

CommunicationThread1 thread1 = new CommunicationThread1(shareEntity);

CommunicationThread2 thread2 = new CommunicationThread2(shareEntity);

thread1.start();

thread2.start();

}

结果

thread1-set-name-0

thread1-set-name-1

thread1-set-name-0

thread1-set-name-1

thread1-set-name-0

thread1-set-name-1

thread1-set-name-0

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值