【问题标题】:How to achieve multi threading while one thread is at sleep mode如何在一个线程处于睡眠模式时实现多线程
【发布时间】:2013-01-18 14:33:43
【问题描述】:

我有一个问题,我的类在执行第一个 run 方法之后没有进入第二个覆盖的 run 方法。

程序执行在一个控制器类中,它有一个main方法和一个线程池:

public class RunnableController {
    // Main method
    public static void main(String[] args) throws InterruptedException {
        try {
            RunnableController controller = new RunnableController();
            controller.initializeDb();
            controller.initialiseThreads();
            System.out.println("Polling");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initialiseThreads() {      
        try {
            threadExecutorRead = Executors.newFixedThreadPool(10);
            PollingSynchronizer read = new PollingSynchronizer(incomingQueue, dbConncetion);
            threadExecutorRead.submit(read);
        } catch (Exception e){
            e.printStackTrace();
        }   
    }
}

我的 poller 类获取新数据并应该进行模拟更新:

public class PollingSynchronizer implements Runnable {
   public PollingSynchronizer(Collection<KamMessage> incomingQueue,
         Connection dbConnection) {
      super();
      this.incomingQueue = incomingQueue;
      this.dbConnection = dbConnection;
   }

   private int seqId;

   public int getSeqId() {
      return seqId;
   }

   public void setSeqId(int seqId) {
      this.seqId = seqId;
   }

   // The method which runs Polling action and record the time at which it is done
   public void run() {
      int seqId = 0;

      while (true) {
         List<KamMessage> list = null;

         try {
            list = fullPoll(seqId);

            if (!list.isEmpty()) {
               seqId = list.get(0).getSequence();
               incomingQueue.addAll(list);
               this.outgoingQueue = incomingQueue;
               System.out.println("waiting 3 seconds");
               System.out.println("new incoming message");
               Thread.sleep(3000);//at this wait I should execute run()

               //when I debug my execution stops here and throws " Class not found Exception "
               // its does not enters the message processor class 
               MessageProcessor processor = new MessageProcessor() {
                  //the run method which should fetch the message processor class.
                  final public void run() {
                     MessageProcessor(outgoingQueue).generate(outgoingQueue);
                  }
               };
              new Thread(processor).start();
            }
         } catch (Exception e1) {
            e1.printStackTrace();
         }
      }
   }
}

我的消息处理器类:

public abstract class MessageProcessor implements Runnable {
   private Connection dbConnection;
   Statement st = null;
   ResultSet rs = null;
   PreparedStatement pstmt = null;
   private Collection<KamMessage> outgoingQueue;

   public KamMsg804 MessageProcessor(Collection<KamMessage> outgoingQueue,
         Connection dbConnection) {
      this.outgoingQueue = outgoingQueue;
      this.dbConnection = dbConnection;
      return (KpiMsg804) fetchedMessages;
   }

   public Collection<KamMessage> generate(Collection<KamMessage> outgoingQueue) {
      while (true) {
         try {
            while (rs.next()) {
               KamMessage filedClass = convertRecordsetToPojo(rs);
               outgoingQueue.add(filedClass);
            }

            for (KamMessage pojoClass : outgoingQueue) {
               KamMsg804 updatedValue = createKamMsg804(pojoClass);
               System.out.print(" " + pojoClass.getSequence());
               System.out.print(" " + pojoClass.getTableName());
               System.out.print(" " + pojoClass.getAction());
               System.out.print(" " + updatedValue.getKeyInfo1());
               System.out.print(" " + updatedValue.getKeyInfo2());
               System.out.println(" " + pojoClass.getEntryTime());
            }
            return outgoingQueue;
         } catch (SQLException e) {
            e.printStackTrace();
         }
      }
   }
}

我的问题恰好在第二次运行(9 方法中,我在 MessageProcessor 类中遇到异常,它会循环回 Polling。

  1. 如何在这里实现多线程,因为当线程在轮询中休眠 3 秒时,它应该同时更新数据库。
  2. 之后,如何将数据反馈和更新回数据库。

我的程序流程 - 我有三个课程: 1.控制器 2.轮询同步 3.消息处理器

我有数据库记录,这些记录被转换成 POJO 形式并存储在 Collection 中。使用这些 POJO,我的课程尝试一次性完成多处理和更新。

  1. Controller - 拥有线程池,使用 poll 方法启动 poller 类 - 完成

  2. 轮询器 - 应该轮询新的传入消息并将其存储在传入队列中 - 完成

  3. MsgProcessor - 应该寻找新的传入消息并将它们从传出队列传递到传入队列 - 也完成了

问题:

现在我的问题是

  1. 我必须在轮询线程休眠 3 秒时实施此更新,

  2. 在我的 Poller 类中第二个 void run() 方法的代码中,传出队列未传递并馈送到消息处理器类进行更新。我的执行流程只是循环回到第一个运行方法并得到 Class 异常。

请帮我解决这些问题。

【问题讨论】:

  • 这将有助于发布确切的异常消息和堆栈跟踪。
  • @matt b 谢谢,我得到异常没有明确的返回值。
  • 我认为您的问题是您的代码混合了糟糕和混乱的代码以及不明确的执行流程。我的建议,扔掉你所拥有的。首先尝试在一张纸上可视化您的流程和执行。然后隔离并实施每个单独的流程。之后,看看如何并行化和线程化它(如果你必须这样做的话)。
  • 另一件事:永远不要将方法命名为构造函数(就像您的 MessageProcessor 方法一样)。这非常令人困惑,而且编码真的非常糟糕。
  • 退后一步。忘记类和对象——识别信息流。数据来自哪里,您应该如何处理它以及应该将其发送到哪里。然后找出流程的哪些部分相互依赖,以及如何以及哪些可以并行运行多个。

标签: java multithreading threadpool


【解决方案1】:

我不能粉饰这个,你的代码是一团糟。但是,至于为什么您的消息处理器代码没有被执行,您实际上从未启动使用此代码创建的线程:

MessageProcessor processor = new MessageProcessor() {
    // the run method which should fetch the message processor class.
    final public void run() {
         MessageProcessor(outgoingQueue).generate(outgoingQueue);                    
    }
};

忽略被调用的混淆命名方法,您的代码应该看起来更像这样:

Message processor = new MessageProcessor() {
    // the run method which should fetch the message processor class.
    final public void run() {
         MessageProcessor(outgoingQueue).generate(outgoingQueue);                    
    }
};

new Thread(processor).start();

【讨论】:

  • 不是语法错误。不幸的是,它允许命名像构造函数这样的方法......
  • 哇,甚至没有注意到这一点。这就是我们支持 Java 命名约定的原因。编辑答案。
  • @Perception am Braindead.. 更正后再次出现此问题... PollingSynchronizer$1.run(PollingSynchronizer.java:86) 处的线程“Thread-1”中的异常 java.lang.NullPointerException java.lang.Thread.run(Unknown Source)
  • 在深入讨论之前,我建议您听取@pap 等的建议,并考虑此处真正需要完成的任务,并将您的代码重构为更简单、更直接。 KISS真的是个好原理!现在,至于您的 NPE,我只能在没有看到堆栈跟踪的情况下猜测,但您可能想检查您的 MessageProcessor 方法是否未尝试访问未初始化的变量。
  • @Perception 谢谢你,我会让我的代码有点容易理解并尽快更新它......感谢你的好意建议,这个社区对我有很大帮助...... :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-10
  • 2011-02-09
  • 1970-01-01
  • 2012-01-11
  • 1970-01-01
  • 1970-01-01
  • 2018-08-09
相关资源
最近更新 更多