我正在寻找一种停止/终止线程的方法,我发现 Thread.stop() 已被弃用。所以我开始寻找另一个解决方案,并看到多个帖子建议这样做:
thread.interrupt();
thread = null;
但这不会阻止我的线程,我的线程看起来像这样:
public static Thread loadingSpinnerTimer (final Context context, final ImageView imageView){
final Handler mHandler = new Handler();
thread = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while (!isPaused) {
try {
Thread.sleep(100);
mHandler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
// Write your code here to update the UI.
Log.e("ThreadMessage","HasRun");
if (ticker == 12){
ticker = 0;
}
Bitmap myBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.spinner_160x160);
Bitmap img = Bitmap.createBitmap(myBitmap.getWidth(), myBitmap.getHeight(), Bitmap.Config.ARGB_8888); //ARGB_8888 transparrent?
Canvas canvas = new Canvas(img);
int offset = myBitmap.getWidth()*ticker;
Rect srcrectangle = new Rect( 0, offset, myBitmap.getWidth(), myBitmap.getWidth()+offset);
Rect dstrectangle = new Rect( 0, 0, myBitmap.getWidth(), myBitmap.getWidth());
canvas.drawBitmap(myBitmap,srcrectangle,dstrectangle,null);
img.setHeight(myBitmap.getWidth());
imageView.setImageDrawable(new BitmapDrawable(context.getResources(), img));
ticker++;
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
});
thread.start();
return thread;
}
有人能找到我可以用来停止/杀死我的线程的解决方案吗?任何帮助深表感谢。
最佳答案
您有一个 while 循环并检查 isPaused
,然后在循环末尾捕获常规 Exception
。即使抛出InterruptedException
,它也会被捕获,然后再次重新运行while循环。
当您捕获 InterruptedException
异常时,您需要将 isPaused
更改为 true,以便 while 循环停止运行。
关于java - 寻找一种方法来停止/杀死线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26302502/