反正是否有线程在运行并在特定时间运行另一个线程时停止? [英] Is there anyway to stop a thread when it's running and running another thread at specific time?

查看:53
本文介绍了反正是否有线程在运行并在特定时间运行另一个线程时停止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

再次是我。我这里有一些问题。这是代码



It''s me again. I have some problem here. Here is the code

class Thread1 extends Thread {
    int i=0;
    public void run(){
            try{
                for(i=0; i<10; i++){
                    System.out.println("Print this 10 times");
                    System.out.println("Timer: "+(i+1));
                    Thread.sleep(1000);
                }
            }
            catch(Exception ex){}
        }
    }

class Thread2 extends Thread {
    public void run(){
        try{
            for(int i=0; i<10; i++){
                System.out.println("Timer: "+(i+1));
                Thread.sleep(1000);
            }
        }
        catch(Exception ex){}
    }
}





每个线程在10秒内运行。



现在必须用这个创建主线程请求:执行程序并首先运行Thread1。然后在5秒后,停止Thread1并运行Thread2。然后在10秒后终止程序。当然:没有触及Thread1和Thread2。



我试过System.currentTimeMillis()但没有运气。有没有其他方法来衡量线程的运行时间并在特定点停止?



非常感谢!



Each thread run in 10 seconds.

Now is must create the main thread with this request: Execute the program and run the Thread1 first. Then at 5 seconds, stop Thread1 and run Thread2. Then terminate the program at 10 seconds. And of course: without touching Thread1 and Thread2.

I tried System.currentTimeMillis() but no luck. Are there any other way to measure the thread''s running time and stop it at specific point?

Thank you very much!

推荐答案

您应该将线程终止逻辑放在线程的代码中并在那里处理终止条件,而不是从外部监视并从父进程中删除线程。如果没有正常终止,线程(以及光纤和进程)可以做坏事。如果你在一个线程中实现''hari kari''逻辑,它就能够自我清理并在死前绑定松散的端点。
You should put the thread termination logic in the thread''s code and handle termination condition(s) there instead of monitoring externally and killing off threads from the parent process. Threads (and fibers and processes) can do bad things if not terminated gracefully. If you implement ''hari kari'' logic within a thread, it will be able to clean itself up and tie up loose ends before dying.


http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html [ ^ ]。


这篇关于反正是否有线程在运行并在特定时间运行另一个线程时停止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆