当前位置 : 主页 > 编程语言 > java >

java160-interrupt方法

来源:互联网 收集:自由互联 发布时间:2022-07-13
import java . util . PrimitiveIterator ; public class Classroon implements Runnable { private Thread student ; //学生线程 private Thread teacher ; //老师线程 public Classroon (){ student = new Thread ( this , "小迷糊" ); teacher

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

运行结果

java160-interrupt方法_测试类

 



上一篇:java159-两个线程共同完成1到100计算
下一篇:没有了
网友评论