?? machine.java
字號:
package interrupt;
import java.util.*;
public class Machine extends Thread{
private int a=0;
private Timer timer=new Timer(true);
public synchronized void reset(){a=0;}
public void run(){
while(true){
synchronized(this){
while(a>3){
final Thread thread=Thread.currentThread();
timer.schedule(new TimerTask(){ //定義一個繼承TimerTask的匿名類
public void run(){
System.out.println(thread.getName()+" has waited for 3 seconds");
thread.interrupt(); //中斷阻塞
}
},3000);
try{
this.wait(); //如果等待時間超過3秒,會收到InterruptedException
}catch(InterruptedException e){
System.out.println(thread.getName()+ " is interrupted");
return;
}
}
a++;
System.out.println("a="+a);
}
}
}
public static void main(String args[])throws Exception{
Machine machine=new Machine();
machine.start();
}
}
/****************************************************
* 作者:孫衛琴 *
* 來源:<<Java面向對象編程>> *
* 技術支持網址:www.javathinker.org *
***************************************************/
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -