我想调用Thread.currentThread()。interrupt(); 下面代码中的方法导致中断,并且Logcat打印输出,Log.e(“”,“ interrupted” + e.toString()); 但是,为此,我需要从interruptThread()方法内部访问运行runnable的线程。它是StopIt类的成员类。
但是,在interruptThread()方法中运行的所有代码都在主UI线程上运行。因此,当我调用Thread.currentThread()。interrupt()时,将在主UI线程上调用它。
我如何从interruptThread()方法内部访问正在运行Runnable的辅助线程或后台线程?
public class StopIt implements Runnable {
@Override
public void run() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// this Log message should print out if working correctly
// when the interruptThread() method below is called on this Thread
Log.e("", "interrupted " + e.toString());
}
}
public void interruptThread() {
// determines which thread this code is running on,
// UI or other thread
// returns true if the thread is the UI thread
if(Looper.myLooper() == Looper.getMainLooper()) {
Log.e("Thread check", "MAIN UI THREAD"); // <-- RESULT OF TEST
} else {
Log.e("Thread check", "other thread NOT main UI thread");
}
// calls interrupt on the main UI thread not the Runnable
// how to get this to interrupt the Runnable thread above?
Thread.currentThread().interrupt();
}
}
将Kevik的评论转换为答案:
创建一个Thread对象作为StopIt类的成员,Thread internalThread = null; ,并在run方法中,internalThread = Thread.currentThread(); 然后在interruptThread()方法中调用internalThread.interrupt()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句