3
我班有以下功能:https://codeshare.io/kvze0
爲什麼我的線程在嘗試關閉後仍然處於活動狀態?
public void startFtp(String address, int port, String username, String password, String filepath, String file)
{
//...parsing parameter to class variables
try {
while (download) {
downloadAndBroadcast();
}
} catch (Exception e){
Log.d(TAG, "startFtp disconnected or fails");
e.printStackTrace();
}
}
private void downloadAndBroadcast() {
beginTime = System.currentTimeMillis();
try {
URL url = new URL("http://" + serverAddress + "/" + serverFile);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
inputStream = new BufferedInputStream(url.openStream());
long difference;
byte data[] = new byte[4094];
int count;
while ((count = inputStream.read(data)) != -1 && download) {
downloadCount += count;
long stoptime = System.currentTimeMillis();
difference = stoptime - beginTime;
if (difference > 1000 && download) {
currentSpeed = downloadCount/(difference/1000L);
averageSpeed = (averageSpeed + currentSpeed)/2;
broadcastSpeed();
downloadCount = 0;
beginTime = stoptime;
}
}
clearInputStream();
} catch (Exception e) {
Log.d(TAG, "FAIL");
e.printStackTrace();
} finally {
clearInputStream();
Log.d(TAG, "downloadAndBroadcast: finally");
}
}
private void broadcastSpeed() {
Log.d(TAG, "broadcastSpeed: ");
toMainActivityIntent = new Intent(Constants.BROADCAST_SPEED)
.addCategory(Intent.CATEGORY_DEFAULT)
.putExtra("speed", averageSpeed)
.putExtra("thread", String.valueOf(Thread.currentThread().getId()));
downloadService.sendBroadcast(toMainActivityIntent); //send to main activity, in main activity, there is a listener that analyzes Broadcast and Intent
}
private void clearInputStream() {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void stopDownload() {
Log.d(TAG, "stopDownload: ");
download = false;
}
我打電話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();
}
}
});
我打電話executor.shutdownNow();
閉上線程下來:
private class MainActivityReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
executor.shutdownNow();
}
}
添加此我想你會一直用的AsyncTask更好。但無論如何 - 我看不到'shutdownNow()'的調用,以及它應該如何調用'stopDownload'? – Fildor
@Fildor調用shutDownNow()在另一個函數中被調用。 –
我以爲我有答案,但我意識到這是錯誤的...你可以驗證下載標誌實際上設置爲false?我不這麼認爲。 – Fildor