转移到Runnable

时间:2015-07-01 12:37:53

标签: java multithreading

我有一些遗留代码,这是从带有main方法的类调用来强制关闭应用程序并停止可能正在运行的所有删除线程。

private void stopFileDeletionThreads() {
    //as activeCount could be wrong, repeat it until no DeletionThread is found
    boolean bFound = false;
    while (true) {
        bFound = false;
        ThreadGroup tg = Thread.currentThread().getThreadGroup();
        if (tg != null) {
            int count = tg.activeCount();
            Thread[] tArray = new Thread[count];
            tg.enumerate(tArray);
            for (int i = 0; i < count; i++) {
                if (tArray[i].getClass().equals(DeletionThread.class)) {
                    bFound = true;
                    ((DeletionThread) tArray[i]).setRunStatus(false);
                }
            }
        }
        if (!bFound) {
            break;
        }
    }
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        _logger.finest("Ignored interrupted exception when waiting after thread directory removal.");
    }
}

这是DeletionThread:

public class DeletionThread extends Thread {
private File _fDirToDelete;
private boolean _bRun;

/**
 * Constructor.
 * @param fDirToDelete direcotory to remove.
 */
public HsaBrokerDeletionThread(File fDirToDelete) {
    _fDirToDelete = fDirToDelete;
    _bRun = true;
}

/**
 * Thread run method.
 */
public void run() {
    if (_fDirToDelete == null) {
        return;
    }
    if (!_fDirToDelete.exists()) {
        return;
    }
    removeFolders(_fDirToDelete);
}

private void removeFolders(File f) {
    if (f == null) {
        return;
    }
    if (!_bRun) {
        return;
    }
    if (f.isDirectory()) {
        File fChildren[] = f.listFiles();
        if (fChildren != null) {
            for (File fTmp : fChildren) {
                if (!_bRun) {
                    return;
                }
                removeFolders(fTmp);
            }
        }
    }
    f.delete();
}


public void setRunStatus(boolean bRun) {
    _bRun = bRun;
}

启动删除线程的代码在另一个类中:

DeletionThread dt = new DeletionThread(f);
dt.start();

我正在使用ExecutorService和Runnable类而不是扩展Thread。如果上述内容如下:

ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(new DirectoryRemover(directory));
executorService.shutdown();

我怀疑当应用程序强行关闭以停止这些删除线程时,如何在stopFileDelectionThreads中复制代码。也许这不是必要的,或者我可以使执行程序服务与守护程序线程一起工作但我在使用i / o时读到这不是一个好主意。

另一个想法是,不是每次在方法中创建一个newSingleThreadExecutor,而是有一个newCachedThreadPool实例,可以使用getmethod访问并在此处调用shutdown。但后来我不确定。

请记住,我不能重写所有内容,小步骤。感谢。

1 个答案:

答案 0 :(得分:0)

  

我正在使用ExecutorService和Runnable类而不是扩展Thread。

extends Thread转换为implements Runnable实际上几乎是微不足道的,只要代码不做愚蠢的事情。

class MyThread extends Thread {

    /**
     * Thread run method.
     */
    public void run() {
        System.out.println("Do something as a Thread.");
    }

}

class MyRunnable implements Runnable {

    /**
     * Thread run method.
     */
    public void run() {
        System.out.println("Do something as a Runnable.");
    }

}

public void test() {
    // Start the `Thread`
    Thread t = new MyThread();
    t.start();
    // Start the `Runnable`.
    Thread r = new Thread(new MyRunnable());
    r.start();
}

我提到的愚蠢的内容包括调用sleep()而不是Thread.sleep()等等,并且通常可以简单地修复。

如何将现有代码转换为使用Executors这一不太重要的问题确实需要更多细节,例如触发创建DeletionThread的内容。