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

凯维克

我想调用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();

 }

}
TomerZ

将Kevik的评论转换为答案:

创建一个Thread对象作为StopIt类的成员,Thread internalThread = null; ,并在run方法中,internalThread = Thread.currentThread(); 然后在interruptThread()方法中调用internalThread.interrupt()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

从Runnable内部访问线程

从Runnable类内部访问共享变量

如何在多线程类中使用实现Runnable的方法

从实现 Runnable 的外部类访问 UI 线程或主线程

如何从类外部访问类内部的方法

如何从我的方法外部访问c Sharp中的对象?

Java-调用线程上的start方法:如何将其路由到Runnable接口的run()?

Java Runnable访问类的对象

如何在可运行的Runnable内部隐藏JavaFX组件?

如何从Java的内部Thread Runnable方法获取返回值?

通过实现runnable来运行线程

实现不带线程的Runnable的Java类

当无法在UI线程上运行Runnable时,如何延迟生成的线程?

如何使在方法外部定义的变量在 jsr223 示例 groovy 脚本中在方法内部使用

Angular:如何从$ http.get方法外部访问angular $ scope.ng-model_name?

如何从onPostRender方法外部访问TinyMCE 4中生成的按钮实例?

如何在方法外部访问const(Discord.js Bot开发)

如何在函数内部但在子函数外部访问var

Java-新线程Runnable中的super关键字-通过类引用非静态方法

实现Runnable的类内的线程字段,实例化所述类

Java:线程调用Runnable

返回值的Java Runnable run()方法

如何停止在 UIThread 上运行的 Runnable

如何测试类用JUnit实现Runnable

如何向Runnable类添加断点

如何让 AtomicInteger 在 Runnable 类中工作

春季启动:在Runnable的静态线程访问自动装配Autowired组件

将Runnable实例传递给Thread会调用Thread的子类的run()而不是Runnable类的run()

当我在单独的线程上运行类(实现Runnable)时,为什么会收到“ android.os.NetworkOnMainThreadException”?