等待唤醒机制让数据依次出现:
举例:以学生类为例子
学生是资源,可以对学生的属性进行赋值。
1.学生类:
2.设置学生属性的类:
3.获取学生属性的类:
4.测试类:
先定义学生类:
public class Student {
private String name;
private int age;
private boolean flag = false;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public Student() {
}
public synchronized void set(String name, int age) {
if (flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.name = name;
this.age = age;
flag = true;
this.notify();
}
public synchronized void get() {
if (!flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(this.name + "..." + this.age);
flag = false;
this.notify();
}
}
再定义SetStudent类:
public class SetStudent implements Runnable {
private Student s;
public SetStudent(Student s) {
this.s = s;
}
public void run() {
int i = 0;
while (true) {
if (i % 2 == 0) {
s.set("潮汐猎人", 26);
} else {
s.set("火女", 24);
}
i++;
}
}
}
然后是GetStudent类:
public class GetStudent implements Runnable {
private Student s;
public GetStudent(Student s) {
this.s = s;
}
public void run() {
while (true) {
s.get();
}
}
}
最后是测试类:
public class Test {
public static void main(String[] args) {
Student s = new Student();
SetStudent ss = new SetStudent(s);
GetStudent gs = new GetStudent(s);
Thread t1 = new Thread(ss);
Thread t2 = new Thread(gs);
t1.start();
t2.start();
}
}
|
|