等待唤醒:
Object类中提供了三个方法:
wait():等待
notify():唤醒单个线程
notifyAll():唤醒所有线程
为什么这些方法不定义在Thread类中呢?
这些方法的调用必须通过锁对象调用,而我们刚才使用的锁对象是任意锁对象。
所以,这些方法必须定义在Object类中。因为他才代表任意对象
public class Student {
String name;
int age;
boolean flag;//默认情况是没有数据
}
public class SetThread implements Runnable{
private Student s=new Student();
private int x=0;
public SetThread(Student s){
this.s=s;
}
@Override
public void run() {
while(true){
synchronized (s) {
//判断有没有
if(s.flag){
try {
s.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(x%2==0){
s.name="张三";
s.age=24;
}else{
s.name="李四";
s.age=34;
}
x++;
//修改标记
s.flag=true;
//唤醒线程
s.notify();
}
}
}
}
public class GetThread implements Runnable {
private Student s = new Student();
public GetThread(Student s) {
this.s = s;
}
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
synchronized (s) {
if(!s.flag){
try {
s.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(s.name + "---" + s.age);
//修改标记
s.flag=false;
//唤醒等待
s.notify();
}
}
}
}
/*
* 分析:
* 资源类:Student
* 设置学生数据:SetThread(生产者)
* 获取学生数据:GetThread(消费者)
* 测试类:StudentDemo
*/
public class StudentDemo {
public static void main(String[] args) {
//创建资源
Student s=new Student();
//设置和获取的类
SetThread st=new SetThread(s);
GetThread gt=new GetThread(s);
//线程类
Thread t1=new Thread(st);
Thread t2=new Thread(gt);
t1.start();
t2.start();
}
}