如何在java中重启线程? [英] How to restart thread in java?

查看:181
本文介绍了如何在java中重启线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个在源文件夹中搜索文件的程序。如果找到任何文件,它会处理该文件并将其移动到目标文件夹,然后在源文件夹中查找新文件。它必须继续检查文件的源文件夹。

I have created a program which searches for files in a source folder. If it finds any file, it processes that file and moves it to a destination folder, then looks for a new file in the source folder. It has to keep on checking the source folder for a file.

我已经使用线程来查找源文件夹中的文件。我遇到的问题是每当在文件处理期间抛出任何异常,线程都将被停止。即使抛出异常,我也希望线程运行。它必须将导致错误的文件移动到某个其他文件夹,并在源文件夹中查找一个新文件。如何让线程继续运行?

I have used a thread to look for files in the source folder. The problem I am facing is whenever any exception is thrown during file processing, the thread gets stopped. I want the thread to be running even if an exception is thrown. It has to move the file that caused the error to some other folder and look for a new file in the source folder. How can I make the thread keep on running?

例如:

public void run() {
    try {
        searchfile();
    }
    catch(Exception e) {
        e.printStackTrace();
    }
}

public void searchfile(){
  ...
}






更新

我的问题应该更清楚实际上有4个源文件夹和4个目标文件夹。我必须在每个来源&目的地对。所以我在一个类中创建了4个线程,并在单独的类中执行操作。

I should be more clear in my question. Actually there are 4 source folders and 4 destination folders. I have to perform the same operation in each source & destination pair. So i have created 4 threads in one class and do the operation in separate class.

class MainClass
{
   public static void main(String[] args){
      for(int i=0;i<4;i++){
         SearchClass search = new SearchClass();
         Thread thread = new Thread(search);
         thread.start();
     }
   }   
}

class SearchClass
{
   public void run() {
   try {
      searchfile();
   } catch(Exception e) {
      e.printStackTrace();
   }
}

public void searchfile(){ ... } }

所有的线程都不会停止运行,而在中间捕获任何异常。如何做到这一点?

All the thread wont stop running eventhough it caught any exception in middle. How can i do that?

推荐答案

如果线程由于未捕获的异常而死亡,答案很简单:捕获异常在适当的地方,以便您能继续前进。或者在searchfile方法中捕获异常,或者使run方法在循环中调用searchfile。

If a thread is dying due to an uncaught exception, the answer is simple: catch the exception at an appropriate place so that you can keep going. Either catch the exception within your searchfile method, or make the run method call searchfile in a loop.

这篇关于如何在java中重启线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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