简体   繁体   English

如何访问在Runnable类内部但在run方法外部运行Runnable的线程?

[英]how to access the thread running the Runnable inside a Runnable class but outside of the run method?

i want to call the Thread.currentThread().interrupt(); 我想调用Thread.currentThread()。interrupt(); method in the code below to cause an interrupt and the Logcat to print out, Log.e("", "interrupted " + e.toString()); 下面代码中的方法导致中断,并且Logcat打印输出,Log.e(“”,“ interrupted” + e.toString()); however in order to this i need to access the thread running the runnable from inside the interruptThread() method. 但是,为此,我需要从interruptThread()方法内部访问运行runnable的线程。 It is a member class of the StopIt class. 它是StopIt类的成员类。

however any code running inside the interruptThread() method is running on the main UI thread. 但是,在interruptThread()方法中运行的所有代码都在主UI线程上运行。 so when i call Thread.currentThread().interrupt() it is called on the main UI thread. 因此,当我调用Thread.currentThread()。interrupt()时,将在主UI线程上调用它。

how to i get access to the worker or background thread that is running the Runnable from inside the in interruptThread() method? 我如何从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();

 }

}

Converting Kevik's comment to an answer: 将Kevik的评论转换为答案:

creating a Thread object as member of the StopIt class,, Thread internalThread = null; 创建一个Thread对象作为StopIt类的成员,Thread internalThread = null; , and inside the run method, internalThread = Thread.currentThread(); ,然后在run方法中,internalThread = Thread.currentThread(); and then call internalThread.interrupt() in the interruptThread() method 然后在interruptThread()方法中调用internalThread.interrupt()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM