如何处理正在轮询的线程池,而另一个应该在处理后更新新的传入数据。 程序执行在一个控制器类中,它有一个主方法和线程池:
主类控制器
public static void main(String[] args) throws InterruptedException {
RunnableController controller = new RunnableController();
Accumulator acque = new Accumulator();
controller.initializeDb();
controller.initialiseThreads(acque);
controller.initialUpdate(acque);
}
轮询类的Run方法:
public void run() {
int seqId = 0;
List<KpiMessage> list = null;
while(true) {
try{
list = fullPoll(seqId);
if (!list.isEmpty()) {
accumulator.manageIngoing(list);
}
} catch (Exception e){
e.printStackTrace();
}
}
}
public List<KpiMessage> fullPoll(int lastSeq) throws Exception {
Statement st = dbConnection.createStatement();
System.out.println("Polling");
ResultSet rs = st.executeQuery("Select * from msg_new_to_bde where ACTION = 804 and SEQ >" +
lastSeq + "order by SEQ DESC");
return pojoCol;
}
运行处理方法:
public void run() {
try {
generate(accumulator.outgoingQueue);
accumulator.manageOutgoing(accumulator.outgoingQueue, dbConnection);
} catch (Exception e) {
e.printStackTrace();
}
}
}
更新到数据库的方法
public void updateDb(Collection<KpiMessage> updatedQueue, Connection dbConnection) throws
SQLException{
for(KpiMessage pojoClass : updatedQueue){
Statement stmtupd = dbConnection.createStatement();
System.out.println("Updating");
String query = "UPDATE msg_new_to_bde SET KEYINFO1= 'Processed', KEYINFO2 = 'Updated'
WHERE ACTION = 804";
stmtupd.executeUpdate(query);**My Execution stops here**
最后是一个用于维护所有这些队列的累加器类:
public boolean isUsed = false;
public synchronized void manageIngoing(List<KpiMessage> list){
if(this.isUsed){
try {
wait();
System.out.println("first wait");
} catch (Exception e1) {
e1.printStackTrace();
}
}
System.out.println("recived pass after update");
this.getIncomingQueue().addAll(list);
//incoming queue copied to outgoing queue
this.setOutgoingQueue(this.getIncomingQueue());
System.out.println("waiting");
System.out.println("new incoming message");
this.isUsed = false;
notifyAll();
}
/**
* Method which handles synchronization using wait and notify for outgoing messages after
polling
* @param outgoingQueue
* @param dbConnection
*/
public synchronized void manageOutgoing(Collection<KpiMessage> outgoingQueue, Connection
dbConnection){
if(!this.isUsed)
{
try {
System.out.println("second wait");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.isUsed = true;
DBhandler dbhandler = new DBhandler();
try {
dbhandler.updateDb(getOutgoingQueue(), dbConnection);
} catch (SQLException e) {
e.printStackTrace();
}
notifyAll();
}
}
我的任务和问题是:
1.控制器应处理线程Poller&amp; amp;处理器和累加器处理传入和传出队列,最后进入更新队列以便在处理后更新数据库
2.我这里的课只做一次轮询,无法更新,执行停止
3.我的wait(),notifyALL()句柄在这里是正确的。
如何在此处实现重复轮询和更新?
答案 0 :(得分:3)
在这个有五个不同问题的复杂环境中,很可能没有完整的答案。在等待这些时,您应该了解java.util.concurrent提供的内容,尤其是支持阻塞读写的并发集合。仅当JDK类不够用时才使用wait()
和notify()
。