1,第一步定义一个学生类
public class Student {
public Student(int age){
this.age=age;
}
int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
第二步,定义一个用来专门做年龄增长的类
package test;
class CheckAgeThread extends Thread {
public Object lock;
Student stu;
public CheckAgeThread(Object lock,Student stu){
this.lock =lock;
this.stu=stu;
}
@Override
public void run( ){
chengn();
}
public void chengn(){
synchronized( lock){
if(this.stu.getAge() < 18){
this.stu.setAge(18);
}
lock.notifyAll();
}
}
}
3.第三步定义一个用来监控年龄是否18岁的线程
public class Tongzhi extends Thread {
Object lock ;
Student stu;
public Tongzhi (Object lock,Student stu){
this.lock=lock;
this.stu=stu;
}
@Override
public void run(){
test( );
}
public void test( ){
synchronized (lock) {
while(true){
if(this.stu.getAge()>17){
System.out.println("成年啦");
break;
}else if(this.stu.getAge()<=17){
try {
System.out.println("年龄增长中。。。");
lock.wait();
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
4.第四步运行
public static void main(String[] args) {
Object lock = new Object();
Student stu = new Student(17);
Tongzhi tz = new Tongzhi(lock,stu);
CheckAgeThread check = new CheckAgeThread(lock,stu);
tz.start();
check.start();
}