1.最简单的生产者消费者模式。
- wait :让线程等待,但是它会释放锁的资源。
- notify:唤醒当前对象锁池被等待的线程。
注意:一定要在synchronized 进行执行,持有同一把锁
现在是生产者生产一个消费一个。生产完就等待,读操作,读完就写
package thread_day05;
class Res{
public String name;
public String sex;
//为true 可读不可写,为false可写不可读
public boolean flag = false;
}
//生产者线程
class InThread extends Thread{
public Res res;
public InThread(Res res){
this.res = res;
}
@Override
public void run() {
int count = 0;
while(true){
synchronized (res) {
if(res.flag){ //如果为true可读不可写,写等待
try {
res.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (count == 0) {
res.name = "小红";
res.sex = "女";
} else {
res.name = "小军";
res.sex = "男";
}
count = (count + 1) % 2;
res.flag=true;//标记当前线程为等待
res.notify(); //唤醒写线程
}
}
}
}
class OutThread extends Thread{
public Res res;
public OutThread(Res res){
this.res = res;
}
@Override
public void run() {
while (true) {
synchronized (res) {
if(!res.flag){ //如果为false 就是可写不可读
try {
res.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
System.out.println(res.name + "," + res.sex);
res.flag = false; //读完了就改为false 改为可写不可读
res.notify(); //唤醒写线程去写
}
}
}
}
}
public class Test0001 {
public static void main(String[] args) {
Res res = new Res();
InThread inThread = new InThread(res);
OutThread outThread = new OutThread(res);
inThread.start();
outThread.start();
}
}