案例:给学生设置和获取姓名和年龄。
案例分析:我们把学生对象作为一个资源进行操作,利用设置线程给学生对象设置姓名和年龄,利用获取线程获取姓名和年龄。
图解:
可以看出这是一个单生产单消费问题。
代码实现:
Student – 被设置的资源对应的类
package com.edu_01;
public class Student {
String name;
int age;
}
SetThread – 设置线程
package com.edu_01;
public class SetThread extends Thread{
private Student s;
private int x=0;
public SetThread(Student s){
this.s=s;
}
@Override
public void run() {
while (true) {
synchronized (s) {
if (x%2==0) {
s.name="张三";
s.age=22;
} else {
s.name="李四";
s.age=23;
}
x++;
}
}
}
}
GetThread – 获取线程
package com.edu_01;
public class GetThread extends Thread{
private Student s;
public GetThread(Student s){
this.s=s;
}
@Override
public void run() {
while (true) {
synchronized (s) {
System.out.println(s.name+":"+s.age);
}
}
}
}
StudnetDemo – 测试类
package com.edu_01;
public class StudentDemo {