您的位置:首页 > 编程语言 > Java开发

java停止线程的一个示例

2014-04-25 13:53 459 查看
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();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 线程 thread