使用参数创建新的Thread

时间:2017-11-29 13:37:47

标签: java multithreading threadpool java-threads

在类 CameraMessageFrameWorker 中,我想创建一个新的Thread来处理一些消息。这些类的构成者获得PartialMessageFrame。我将这些PartialMessageFrame复制到新的private变量messageFrame。使用此变量我想创建新的线程,但是当我想要这样做时,我得到一个java.lang.IndexOutOfBoundsException因为这个变量是null

我检查了构造函数中的messageFrame变量是否获得了调用函数的数据。

如何将一些参数放入此线程?这段代码有什么问题?

CameraMessageFrameWorker.java

public class CameraMessageFrameWorker implements MessageFrameWorker {

  private static final Logger LOGGER = LoggerFactory.getLogger(CameraMessageFrameWorker.class);

  private final PartialMessageFrame messageFrame;
  private final SerialPort serialPort;

  public CameraMessageFrameWorker(
      final PartialMessageFrame p,
      final SerialPort serialPort) {
    messageFrame = p;
    this.serialPort = serialPort;
  }

  @Override
  public void run() {
    switch (messageFrame.getMessageType()) {
      case FCT: {
        handleFunction();
        break;
      }
      case REQ: {
        handleRequest();
        break;
      }
      default: {
        LOGGER.warn("unhandled message type");
        break;
      }
    }
  }

接口:MessageFramewoker.java

public interface MessageFrameWorker extends Runnable {
}

错误讯息:

Exception in thread "pool-1-thread-1" java.lang.IndexOutOfBoundsException: Index: 9, Size: 0
    at java.util.ArrayList.rangeCheck(ArrayList.java:653)
    at java.util.ArrayList.get(ArrayList.java:429)
    at com.scape.cx.service.draeger.polaris.simulator.PartialMessageFrame.getMessageTypeAsInt(PartialMessageFrame.java:56)
    at com.scape.cx.service.draeger.polaris.simulator.PartialMessageFrame.getMessageType(PartialMessageFrame.java:80)
    at com.scape.cx.service.draeger.polaris.simulator.CameraMessageFrameWorker.run(CameraMessageFrameWorker.java:39)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

1 个答案:

答案 0 :(得分:0)

要解决此问题,我必须先从此messageFrame制作一份深层副本,然后才能将其放入此CameraMessageFrameWorker

请参阅此处从ArrayList进行深层复制 How to clone ArrayList and also clone its contents?