package 10weeks
import java.util.concurrent.TimeUnit;
public class ClassRoom implements Runnable {
Thread student,teacher;
ClassRoom(){
student=new Thread(this);
student.setName("东东");
teacher=new Thread(this);
teacher.setName("王教授");
}
public void run(){
if(Thread.currentThread()==student){
Stu();
}
else if(Thread.currentThread()==teacher){
Tea();
}
}
public void Stu() {
try{
System.out.println(student.getName()+"正在睡觉,不听课");
TimeUnit.HOURS.sleep(1);
} catch (InterruptedException e) {
System.out.println(student.getName()+"被老师叫醒");
}
System.out.println(student.getName()+"开始听课");
System.out.println(student.getName()+"又开始睡觉");
try {
TimeUnit.HOURS.sleep(1);
} catch (InterruptedException e) {
System.out.println(student.getName()+"再次被叫醒");
}
System.out.println(student.getName()+"被教授罚站!");
return;
}
public synchronized void Tea(){
while (student.isAlive()){
for (int i=0;i<3;i++){
System.out.println("上课!");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
student.interrupt();
}
}
}
public class test13 {
public static void main(String args[]){
ClassRoom room=new ClassRoom();
room.teacher.start();
room.student.start();
}
}