AlternateStop.java
资源名称:Source.rar [点击查看]
上传用户:songled
上传日期:2022-07-14
资源大小:94k
文件大小:1k
源码类别:
进程与线程
开发平台:
Java
- public class AlternateStop extends Object implements Runnable {
- private volatile boolean stopRequested;
- private Thread runThread;
- public void run() {
- runThread = Thread.currentThread();
- stopRequested = false;
- int count = 0;
- while ( !stopRequested ) {
- System.out.println("Running ... count=" + count);
- count++;
- try {
- Thread.sleep(300);
- } catch ( InterruptedException x ) {
- Thread.currentThread().interrupt(); // re-assert interrupt
- }
- }
- }
- public void stopRequest() {
- stopRequested = true;
- if ( runThread != null ) {
- runThread.interrupt();
- }
- }
- public static void main(String[] args) {
- AlternateStop as = new AlternateStop();
- Thread t = new Thread(as);
- t.start();
- try {
- Thread.sleep(2000);
- } catch ( InterruptedException x ) {
- // ignore
- }
- as.stopRequest();
- }
- }