Timer是个计时器。计时时间由调用构造函数的时候的参数决定。Timer每隔规定的时间就会有一个输出。如果输入0会停止计时。
代码如下:
import java.util.Scanner;
class Timer extends Thread{
private long time;
private boolean stopRequested;
public Timer(long time){
this.time=time;
}
public void run() {
stopRequested = false;
int count = 0;
while ( !stopRequested ) {
System.out.println(count);
count++;
try {
Thread.sleep(time);
} catch ( InterruptedException x ) {
this.interrupt();
}
}
System.out.println("stoped");
}
public void stopRun() {
stopRequested = true;
if ( this != null ) {
this.interrupt();
}
}
}
public class MyThread {
public static void main(String[] args) {
Timer timer=new Timer(1000);
timer.start();
Scanner sc=new Scanner(System.in);
int ch=sc.nextInt();
if (ch == 0) {
timer.stopRun();
}
}
}