在特定时间后停止线程

时间:2016-03-22 10:11:40

标签: java multithreading

我想在特定时间后停止我的线程。在这里,我添加了我的示例代码。任何一个线程需要超过6秒意味着我想停止特定线程。其余的线程不应受到影响。我是否需要使用定时器或更好的方法才能实现?假设我使用了Timer意味着我是否需要为每个线程创建新的计时器,如果作业在6secs之前完成,我是否需要取消计时器?

    class MyRunnableThread implements Runnable{

    public static int myCount = 0;
    private String fname = null;
    public MyRunnableThread(String fname){
         this.fname = fname;
    }
    public void run() {

            try{
                //read the content based on text and peforms the operation
                //File.read(this.fname)
                System.out.println("Run method stuff"+ this.fname);
            } catch (Exception iex) {
                System.out.println("Exception in thread: "+iex.getMessage());
            }
    }

}

public class RunMyThread {

    public static void main(String a[]){
        System.out.println("Starting Main Thread...");

        String[] fname = {"file1.txt","file2.txt","file3.txt","file4.txt","file5.txt"};
         for(int i=0;i<5;i++){
            try{
                MyRunnableThread mrt = new MyRunnableThread(fname[i]);
                Thread t = new Thread(mrt);
                System.out.println("Main Thread start "+i);
                t.start();

                //stop the thread support run method takes more than 6seconds
                System.out.println("Main Thread end "+ i );
            } catch (Exception iex){
                System.out.println("Exception in main thread: "+iex.getMessage());
            }
        }
        System.out.println("End of Main Thread...");
    }
}

3 个答案:

答案 0 :(得分:1)

有一种想法是你有一个包含所有线程的ArrayList。

然后你让每个线程都有一个额外的字段(Timestamp started)

然后你有一个定时器循环遍历Arraylist并停止开始的线程&gt; 6秒前

答案 1 :(得分:0)

用户定时器和一个标志告诉线程停止:

$mail->Send()

如何使用它:

public class MyRunnableThread implements Runnable {

    boolean run = true;

    String fname;

    public MyRunnableThread(String fname) {
        this.fname = fname;
    }

    public void setRun(boolean toSet) {
        run = false;
    }

    public void run() {
        while (run) {
            doStuff();
        }
    }

    private void doStuff() {
//       File.read(fname);
    }
}

将i更改为您想要的任何时间

答案 2 :(得分:0)

嗯..有很多方法可以做到,我会解释其中的一个。

您可以创建extends Thread然后实施方法run()CancelCurrentThread()的自定义类,您的投放将启动ThreadCancelCurrentThread()将停止它忽略了例外。

然后您的代码应如下所示:

mCustomThread thread = new mCustomThread(parametres_if_you_need);
thread.start(); //Start the Thread
thread.join(6000);  //Adding 6 seconds
//You can detect if the 6 seconds have passed or not for example using a timer, then if it joins on this if condition you can call
thread.CancelCurrentThread();