日期:2014-05-20 浏览次数:20648 次
import java.util.*; public class MachineInterruptedException 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(){ public void run() { System.out.println(thread.getName()+" has waited for 3 seconds"); thread.interrupt(); } },3000); try { this.wait(); }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 { MachineInterruptedException machine = new MachineInterruptedException(); machine.start(); } }