/*
需求: 有两个线程学生和老师
学生准备睡一会再上课,老师说了3下上课
叫醒睡觉的学生
*/
class ClassRoom implements Runnable
{
Thread teacher,student;
//目标对象将线程作为自己的的成员
ClassRoom()
{
teacher=new Thread(this);
student=new Thread(this);
teacher.setName("王老师");
student.setName("张三");
}
public void run()
{
if(Thread.currentThread()==student)
{
try
{
System.out.println(student.getName()+"正在睡觉");
Thread.sleep(1000*60*60);
}
catch(InterruptedException e)
{
System.out.println(teacher.getName()+"上课了,快醒醒");
}
System.out.println(student.getName()+"醒了,开始听课");
}
else if(Thread.currentThread()==teacher)
{
for(int i=0;i<3;i++)
{
try
{
Thread.sleep(100);
}
catch(InterruptedException e){}
System.out.println("上课!");
}
student.interrupt();//叫醒student
}
}
}
class ClassDemo
{
public static void main(String[] args)
{
ClassRoom room=new ClassRoom();
room.student.start();
room.teacher.start();
}
}
|
|