Java多线程

Java多线程,第1张

Java多线程

张三、李四上课睡觉,王教授喊上课,张三被叫醒开始上课,然后张三把李四叫醒听课

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();
  }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5686002.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存