[英]how to destroy a thread , pause/suspend a thread , resume/runAgain a thread?
大家好,我在android應用程序中的oncreate之外使用runnable,我在其中使用線程來設置ProgressBar的進度。 我不知道的是當按下停止按鈕時如何停止/重試線程,因為thread.stop不是一種方法,以及如何從中恢復,甚至破壞線程。
我知道我必須使某些方法和成員處於可運行狀態,但我不完全知道是什么?
不再使用Thread.stop()
因為它被認為是危險的: http : //download.oracle.com/javase/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html 。
由於變量更改,您必須讓線程自然結束。 該鏈接還提供了有關如何實現此目標的一些建議。
public class MyThread extends Thread {
private boolean threadDone = false;
public void done() {
threadDone = true;
}
public void run() {
while (!threadDone) {
// work here
// modify common data
}
}
}
警告:請確保您在循環代碼中使用受保護的塊 ,一種會自身阻塞的方法或Thread.sleep(..)
。 如果您不了解受保護的塊,則Thread.sleep是其中最原始的,但是它將起作用。 您還可以永遠等待並使用中斷機制來取消使用等待或睡眠時在try-catch塊中作為InterruptedException
拋出的線程。 為此,請使用!Thread.currentThread().isInterrupted()
作為循環保護條件,然后使用您的Thread對象並調用thread.interrupt()
。
您有幾種選擇,它們取決於您如何定義線程的各種狀態。
當線程退出run()方法時,該線程將有效停止。
要“暫停”和“恢復”線程的執行,可以使用wait()和notify()。
為了說明這一點,這是一個簡單的示例:
class MyThread implements Runnable {
private boolean keepRunning = false;
private boolean isPaused = false;
public void run() {
keepRunning = true;
try {
while (keepRunning) {
// do stuff here
if (isPaused) {
synchronized (this) {
// wait for resume() to be called
wait();
isPaused = false;
}
}
}
} catch (Exception ex) {
// do stuff
}
}
// note that as-is this won't do anything to a paused thread until
// it is resumed.
public void stop() {
keepRunning = false;
}
public void pause() {
isPaused = true;
}
public synchronized void resume() {
// notify anybody waiting on "this"
notify();
}
}
要控制Java線程,您應該向該對象添加方法,其他對象可以調用這些方法,這些對象設置了run()
方法讀取的變量。 您沒有給出確切的操作信息,但這是一種可能的模式:
public class ProgressBarUpdater implements Runnable{
private volatile boolean paused = false;
private volatile boolean finished = false;
/* other fields, constructor etc. */
public void run(){
while(!finished){
updateProgressBar();
while(paused && !finished){
try{
Thread.sleep(1000); //Busy wait - should really use wait/notify, but that's another lesson
}
catch(InterruptedException e){
}
}
}
}
public synchronized void pauseProgressBar(){
paused = true;
}
public synchronized void unPauseProgressBar(){
paused = false;
//call notify() here when you switch to wait/notify.
}
public void stopProgressBar(){
finished = true;
//call notify() here too.
}
}
您可能希望對控制變量使用更強大的同步,並且如注釋中所述,等待/通知而不是忙於等待。
如此使用:
ProgressBarUpdater pbu = new ProgressBarUpdater();
Thread t = new Thread(pbu);
t.start();
Thread.sleep(10000); //let the progress bar run for ten seconds.
pbu.pauseProgressBar();
Thread.sleep(10000); //pause it for ten seconds.
pbu.unPauseProgressBar();
Thread.sleep(10000); //restart for another ten seconds.
pbu.stopProgressBar(); //stop progress bar.
讓另一個線程定期檢查布爾標志(isCancelled或類似的東西)。 最初是假的。
在您的停止按鈕代碼中,將此值設置為true。
當您的線程接下來檢查該標志並發現它為true時,該線程應殺死自己。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.