具体来说是线程间的通信问题;
表示为:Student 资源;SetThread 生产线程以及GetThread 消费线程。
void wait ()线程等待
void notify()唤醒等待的单个线程;
生产线程生产好资源后,通知消费线程消费,与此同时再次和消费争抢时间片,但是此时标记为true,表示有资源,就会等待,并释放锁;从而让消费线程消费;依次循环
public class MyTest {
public static void main(String[] args) {
//共享资源
Student student = new Student();
//生产线程
SetThread setThread = new SetThread(student);
//消费线程
GetThread getThread = new GetThread(student);
//启动线程
setThread.start();
getThread.start();
}
}
class Student { //资源
public String name;
public int age;
public boolean flag=false; //false代表没有资源,true代表有资源
}
class SetThread extends Thread{
Student student;
int i=0;
public SetThread(Student student) {
this.student=student;
}
//生产线程:当我生产出一个资源时,等待着,并通知消费者消费
@Override
public void run() {
while (true){
synchronized (student){
if(student.flag){ //表示有资源
try {
student.wait(); //等待,释放锁。从哪里等待,被唤醒后,就从这里醒来
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (i % 2 == 0) {
student.name = "张三";
student.age = 23;
} else {
student.name = "李四";
student.age = 24;
}
//有资源了,通知消费者去消费
student.flag=true; //修改标记
student.notify(); //唤醒消费线程,通知后,两个再次抢占时间片
}
i++;
}
}
}
class GetThread extends Thread{
Student student;
public GetThread(Student student) {
this.student=student;
}
//消费线程:消费了资源,等待着,并通知生产者去生产
@Override
public void run() {
while (true){
synchronized (student){
if(!student.flag){ //消费者:没有资源等待
try {
student.wait(); //等待:wait()方法,一旦等待,就要释放锁
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//消费
System.out.println(student.name + "===" + student.age);
//通知
student.flag=false; //修改标记
student.notify();//通知生产者生产,两个线程再次争抢时间片
}
}
}
}