Java作业五(下)

题目

有3个线程: student1、student2和teacher,其中student1准备睡10分钟后再开始上课,其中student2准备睡1个小时后再开始.上课。Teacher在输出3句“上课”后,吵醒休眠的线程student1,student1被吵醒后,负责再吵醒休眠的线程student2。(即P394 4.编程题第(2)题)

代码

package homework;

class ClassRoom implements Runnable{
	Thread student1,student2,teacher;
	public ClassRoom(){
		student1 = new Thread(this);//必须有this
		student2 = new Thread(this);
		teacher = new Thread(this);
		student1.setName("student1");
		student2.setName("student2");
		teacher.setName("teacher");
	}
	public void run() {
		if(Thread.currentThread() == student1) {
			try {
				System.out.println(student1.getName()+"正在睡觉");
				Thread.sleep(1000*10*60);
			}catch(InterruptedException e) {
				System.out.println(student1.getName()+"被teacher叫醒");
			}
			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叫醒");
			}
			System.out.println(student2.getName()+"开始听课");
		}
		else if(Thread.currentThread() == teacher) {
			for(int i=0;i<3;i++) {
				System.out.println("上课");
				try {
					Thread.sleep(10);
				}catch(InterruptedException e) {}
			}
			student1.interrupt();
		}
		
		}
}
public class work_5 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ClassRoom classRoom = new ClassRoom();
		classRoom.student2.start();
		classRoom.student1.start();
		classRoom.teacher.start();
	}
}

 

1.腾龙梦屋文章内容无特殊注明皆为源儿原创,转载请注明来源,谢谢!
2.若有相关文章侵犯您的权益,请联系源儿删除,谢谢!
3.相关软件、资料仅供学习参考使用,在24h内务必删除!
腾龙梦屋 » Java作业五(下)
加速支持