java - java/android 向循环线程发送消息

标签 java android multithreading loops message

所以我有以下主题:

  public class MyThread extends Thread
{
  Handler cHandler;
 private boolean looprunning = false;
  MyThread() {
  cHandler = new Handler();
          looprunning = true;

  }

  @Override
  public void run(){
      while (looprunning) {
          //do stuff here
        //update another system here or something else.
      }
  }

}

在此线程的 while 循环内,我想运行一个 Runnable,当线程在该 while 循环内循环时,我将其传递给该线程。我该怎么做?

最佳答案

首先请将looprunning标记为 volatile ,以获得正确的线程可见性

您可以使用队列

Queue<Runnable> taskQueue = new ConcurrentLinkedQueue<Runnable>();
@Override
public void run(){
   while (looprunning) {
       //do stuff here
     //update another system here or something else.
     Runnable r = taskQueue.poll();
     if(r!=null)r.run();
   }
} 

您可以使用您选择的(线程安全)队列

关于java - java/android 向循环线程发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10618630/

相关文章:

java - 无法解析证书 : java. io.IOException:空输入 X509Certificate

java - 在 Spring MVC 请求处理程序中调用 Thread.currentThread().sleep(2000) 的第二个请求有什么影响?

python - 运行时错误: threads can only be started once for a beginner

安卓房间 : How to Migrate Column Renaming?

Android Wear 表盘背景动画

android - 在 Debug模式下设置 minifyEnabled true 后 api 调用无法正常工作

Java 线程 : Specifying what should be executed in the run function

java - 使用自定义容器作为 TestContainer 的数据库

java - 没有可用的客户端连接器支持所需的协议(protocol) : 'HTTP'

java - 应用程序在完成()后不会关闭