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();
}
}
}
代码如下:
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中如何停止(stop)一个线程
- java中如何靠着throw抛出一个异常来停止线程
- java如何正确停止一个线程
- Java通过在主循环中判断Boolean来停止线程的方法示例
- java中如何靠interrupt来停止stop一个线程
- Java 如何正确停止一个线程
- 停止一个java的线程执行
- Java再学习——停止一个正在运行的线程
- java通过共享变量结束run停止线程的方法示例
- 如何停止一个正在运行的java线程?
- java如何正确停止一个线程
- 如何在Java代码示例中停止线程
- java 停止一个正在运行的线程
- 0038 Java学习笔记-多线程-传统线程间通信、Condition、阻塞队列、《疯狂Java讲义 第三版》进程间通信示例代码存在的一个问题
- 如何停止一个Java线程
- java中一个子线程如何通过interrupt手段来停止另外一个子线程
- Java中合理的停止掉一个线程thread
- 如何停止一个正在运行的java线程
- java如何正确停止一个线程
- 如何停止一个正在运行的java线程