Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么我的线程在尝试关闭后仍处于活动状态?_Java_Android_Multithreading_Threadpoolexecutor - Fatal编程技术网

Java 为什么我的线程在尝试关闭后仍处于活动状态?

Java 为什么我的线程在尝试关闭后仍处于活动状态?,java,android,multithreading,threadpoolexecutor,Java,Android,Multithreading,Threadpoolexecutor,我的类具有以下功能: 我调用stopDownload()停止线程。之后,我记录ThreadPoolExecutor以查看线程的状态: [Shutting down, pool size = 4, active threads = 4, queued tasks = 0, completed tasks = 0] 什么使我的线程活跃?提前谢谢 如何启动线程: int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();

我的类具有以下功能:

我调用
stopDownload()
停止线程。之后,我记录ThreadPoolExecutor以查看线程的状态:

[Shutting down, pool size = 4, active threads = 4, queued tasks = 0, completed tasks = 0]
什么使我的线程活跃?提前谢谢

如何启动线程:

    int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();

    executor = new ThreadPoolExecutor(
            NUMBER_OF_CORES * 2,
            NUMBER_OF_CORES * 2,
            60L,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>()
    );
    executor.execute(new Runnable() {
        public void run() {
            FTPDownloader ftpDownloader = new FTPDownloader(downloadService);
            ftpDownloader.startFtp(server.getServer(), server.getPort(), server.getUser(), server.getPass(), server.getPath(), server.getFiledl());
            if (Thread.interrupted()) {
                Log.d(TAG, "run: ");
                ftpDownloader.stopDownload();
            }
        }
    });

请尝试以下步骤:

摆脱这些台词:

if (Thread.interrupted()) {
            Log.d(TAG, "run: ");
            ftpDownloader.stopDownload();
        }
下载和广播中
将此添加到
}catch(异常e){


我想你最好使用AsyncTask。但是无论如何,我看不到对
shutdownNow()的调用
,那该如何调用
stopDownload
?@Fildor call to shutdownNow()呢是在另一个函数中调用的。我想我已经知道了答案,但我意识到这是错误的…你能验证下载标志是否真的设置为false吗?我不这么认为。哦,在你的问题中,你写道:“我调用stopDownload()来停止线程”哪个是正确的?您调用stopDownload或关闭Executor?是的。但是您在downloadAndBroadcast中将InterruptedException捕获为异常,这将重置中断状态。然后返回startFTP,它将继续循环,因为下载仍然为真。不过,它应该打印堆栈跟踪。您可以尝试添加catc带有
catch(InterruptedException)
的h-block-before-catch(异常)
,您只需在其中设置
download=false;
private class MainActivityReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
            executor.shutdownNow();       
    }
}
if (Thread.interrupted()) {
            Log.d(TAG, "run: ");
            ftpDownloader.stopDownload();
        }
} catch (InterruptedException ie) {
    // catching IE will reset interrupted status. So just clear the flag.
    download = false;
}