java程序运行过程中如何暂停,恢复?

java程序运行过程中如何暂停,恢复?,第1张

  java控制程序执行,使用的是Thread这个类,可以控制程序暂停或者休眠几秒再执行。示例如下:

public abstract class MyThread extends Thread {  
  
    private boolean suspend = false;  
  
    private String control = ""; // 只是需要一个对象而已,这个对象没有实际意义  
  
    public void setSuspend(boolean suspend) {  
        if (!suspend) {  
            synchronized (control) {  
                controlnotifyAll();  
            }  
        }  
        thissuspend = suspend;  
    }  
  
    public boolean isSuspend() {  
        return thissuspend;  
    }  
  
    public void run() {  
        while (true) {  
            synchronized (control) {  
                if (suspend) {  
                    try {  
                        controlwait();  
                    } catch (InterruptedException e) {  
                        eprintStackTrace();  
                    }  
                }  
            }  
            thisrunPersonelLogic();  
        }  
    }  
  
    protected abstract void runPersonelLogic();  
      
    public static void main(String[] args) throws Exception {  
        MyThread myThread = new MyThread() {  
            protected void runPersonelLogic() {  
                Systemoutprintln("myThead is running");  
            }  
        };  
        myThreadstart();  
        Threadsleep(3000);  
        myThreadsetSuspend(true);  
        Systemoutprintln("myThread has stopped");  
        Threadsleep(3000);  
        myThreadsetSuspend(false);  
    }  
}

有三种方法可以使终止线程
1 使用退出标志,使线程正常退出,也就是当run方法完成后线程终止。
2 使用stop方法强行终止线程。
3 使用interrupt方法中断线程。

首先告诉你线程的安全关闭一般有这么几种方法,一个是设置运行标记量,如
boolean running = true;
Thread t = new Thread(new Runnable(){
public void run() {
while(running) {
//
}
}
};
那么你这个例子也可以类似的为按钮a上的线程添加一个全局运行标志量running,初值为true。在点击按钮b的时候,设置这个标志量为false,则按钮a上的线程就终止了。
另外一种方法就是采用interrupt()方法,不过就要求按钮a上的线程必须对按钮b中的线程可见。

//定义休眠的秒
int n=
try
{
Threadsleep(n1000);
}
catch(InterruptedException e)
{
Systemoutprintln("休眠被中断。");
}

看到的回答确实有点不明不白的。楼主估计已经搞定了吧,应该是这么做的
在你想要暂停的地方加上下面这段程序
try{
Threadsleep(10000);
}catch(Exception e){

}
不需要添加什么包哦,sleep里面的参数就是你要停止的时间,单位是毫秒。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/13336065.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-07-17
下一篇 2023-07-17

发表评论

登录后才能评论

评论列表(0条)

保存