import java.util.PrimitiveIterator;public class Classroon implements Runnable {private Thread student;//学生线程private Thread teacher;//老师线程public Classroon(){student = new Thread( this,"小迷糊" );teacher = new Thread( this,"大教授" );student.setPriority( Thread.MIN_PRIORITY );student.start();teacher.start();}public void run(){Thread current=Thread.currentThread();//获取当前方法的线程if(current==student){//如果是学生线程System.out.println( current.getName()+"在听课" );System.out.println( current.getName()+"不听课,准备睡觉" );try {Thread.sleep( 1000*60*60 );}catch (InterruptedException e){System.out.println( "学生被老师叫醒了,继续听课" );e.printStackTrace();}}if(current==teacher){//如果是老师线程,则吵醒学生System.out.println( "老师上课" );for(int i=1;i<=3;i++){System.out.println( current.getName()+"大声喊,上课了,不要睡觉啊" );try {Thread.sleep( 2000 );}catch (InterruptedException e){e.printStackTrace();}}student.interrupt();//中断student线程的休眠状态}}
}
测试类
public class test107 {public static void main(String[] args){new Classroon();}
}
运行结果