Bootstrap

ROS源码学习 十四、Concurrent(1)j

2021SC@SDUSC

一、简介

        从本节开始,我们将分析Concurrent包,该包为ROS执行各种并发逻辑所依赖的各种类的集合.其中包括线程安全的数据结构、ROS自定义的循环执行线程和ROS封装的Java线程池.

二、CancellableLoop

        CancellableLoop为ROS自定义的一个线程模型,该线程允许被中断,且能够在被中断时执行一系列的自定义逻辑.

        

public abstract class CancellableLoop implements Runnable {

  private final Object mutex;


  private boolean ranOnce = false;

  private Thread thread;

  public CancellableLoop() {
    mutex = new Object();
  }

  @Override
  public void run() {
    synchronized (mutex) {
      Preconditions.checkState(!ranOnce, "CancellableLoops cannot be restarted.");
      ranOnce = true;
      thread = Thread.currentThread();
    }
    try {
      setup();
      while (!thread.isInterrupted()) {
        loop();
      }
    } catch (InterruptedException e) {
      handleInterruptedException(e);
    } finally {
      thread = null;
    }
  }


  protected void setup() {
  }


  protected abstract void loop() throws InterruptedException;


  protected void handleInterruptedException(InterruptedException e) {
  }


  public void cancel() {
    if (thread != null) {
      thread.interrupt();
    }
  }


  public boolean isRunning() {
    return thread != null && !thr
;