张三、李四上课睡觉,王教授喊上课,张三被叫醒开始上课,然后张三把李四叫醒听课。
public class ClassRoom implements Runnable { Thread student1,student2,teacher; ClassRoom(){ student1=new Thread(this); student2=new Thread(this); teacher=new Thread(this); student1.setName("张三"); student2.setName("李四"); teacher.setName("王教授"); } public void run(){ if(Thread.currentThread()==student1){ try{ System.out.println(student1.getName()+"正在睡觉,不听课"); Thread.sleep(1000*60*10); }catch(InterruptedException e){ System.out.println(student1.getName()+"被老师叫醒了"); } System.out.println(student1.getName()+"开始听课"); student2.interrupt(); } else if(Thread.currentThread()==student2){ try{ System.out.println(student2.getName()+"正在睡觉,不听课"); Thread.sleep(1000*60*60); }catch(InterruptedException e){ System.out.println(student2.getName()+"被"+student1.getName()+"叫醒"); } System.out.println(student2.getName()+"开始听课"); } else if(Thread.currentThread()==teacher){ for(int i=1;i<=3;i++) System.out.println("上课!"); try{ Thread.sleep(500); }catch(InterruptedException e){} student1.interrupt(); } } }
public class Homework5 { public static void main(String []args){ ClassRoom classRoom=new ClassRoom(); classRoom.student1.start(); classRoom.student2.start(); classRoom.teacher.start(); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)