欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

浅谈java多线程wait,notify

程序员文章站 2023-11-12 20:29:16
前言 1.因为涉及到对象锁,wait、notify一定要在synchronized里面进行使用。 2.wait必须暂定当前正在执行的线程,并释放资源锁,让其他线程可以有...

前言

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

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