如何创建要从Spring threadpooltaskexecutor

时间:2018-08-24 21:49:59

标签: multithreading spring-boot threadpool runnable threadpoolexecutor

我创建了一个spring threadpooltaskexecutor,用于连续运行从RFID读取器读取的任务。我让它可以处理线程,但是我想让Spring管理它们。现在我将其放入线程池中,它无法正常工作。创建对象后,即使在阅读器前面传递了标签,也不会给出更多信息。

我正在服务中创建读取器以连接到读取器并从消息侦听器服务读取标签。预计将读取5秒钟,并且如果有标签,则将消息通知发送到通知地址。然后暂时将标签打印出来。最终,我将添加代码以对标签执行其他操作。我目前未包含消息通知。

我知道我想念一些东西,但找不到。我知道要看的代码很多,但是我有。

这里是threadpoolexecutor配置:

@Bean
public TaskExecutor threadPoolTaskExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(15);
    executor.setMaxPoolSize(20);
    executor.setThreadNamePrefix("default_task_executor_thread");
    executor.initialize();
    return executor;
}

这是春季服务:

  @Service
public class ReadTags {

@Autowired
    private TaskExecutor taskExecutor;

  public void testMethod() throws UnknownHostException, 
 AlienReaderException, InterruptedException {
AlienReader reader=(AlienReader) applicationContext.getBean("alienReader");
    reader.setIpaddress("111.111.11.11");
    reader.setPort(11);
    reader.setUsername("username");
    reader.setPassword("password");

  taskExecutor.execute(new Runnable(){
        @Override
        public void run(){
            try {
                reader.startMessageService(3700);
                reader.setReaderConfig(reader,3700);
            } catch (UnknownHostException | AlienReaderException | 
 InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
}

这是Alienreader类:

   @Component
@Scope("prototype")
public class AlienReader extends AlienClass1Reader implements MessageListener, TagTableListener, Runnable{
    public AlienReader(String ipAddr, int port, String user, String pwd, String serviceport) throws UnknownHostException, AlienReaderException, InterruptedException{
        super(ipAddr, port);
    this.ipaddress=ipaddress;
    this.port=port;
    this.username=username;
    this.password=pwd;
    this.serviceport=serviceport;

     }
        public void startMessageService(int serviceport) throws 
      UnknownHostException, AlienReaderException, InterruptedException{
  service=new MessageListenerService(serviceport);
         service.setMessageListener(this);
                 try{
                      service.startService();
                        }catch(IOException e){
                         log.info("Error starting MessageListenerService for reader: " + ipAddr);
                         e.printStackTrace();
                    } 


        }

private void setReader(String username, String password) throws UnknownHostException, AlienReaderException, InterruptedException{
        log.info("Setting up reader");
        ...............................rest of code
    }

@Override
    public void run() {
        try{
while(keepRunning){
            Thread.sleep(1000);
}
        }catch(InterruptedException e){
            e.printStackTrace();
        }
    }

0 个答案:

没有答案