当前位置: 移动技术网 > IT编程>开发语言>Java > 浅谈java多线程wait,notify

浅谈java多线程wait,notify

2019年07月19日  | 移动技术网IT编程  | 我要评论

前言

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

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网