多執行緒進行同步資料

2021-09-27 00:01:37 字數 1557 閱讀 8121

開發中會有場景需要對接第三方系統.第三方系統往往會提供乙個中間庫,然後我們系統讀取中間庫的資料,然後經過一系列的邏輯,把資料存到自己系統中. 在這裡分享一種通過生產者,消費者模式進行資料同步,接近實時

主要思路: 乙個生產者執行緒, 實時去中間庫查詢沒有同步的資料.多個消費者,消費生產者生產的資料

1.乙個生產者執行緒, 實時去中間庫查詢沒有同步的資料

2.使用消費者對生產者生產的資料進行同步

3.記錄下處理完成/處理失敗的同步記錄

/**

* 同步中間庫生產者.從中間庫中查詢資料

*/public class producer implements runnable

@override

public void run() catch (interruptedexception e)

}else catch (interruptedexception e) }}

}}

/**

* 同步中間庫消費者.消費生產者的資料

*/public class consumer implements runnable

@override

public void run() catch (exception e)finally catch (interruptedexception e) }}

public listgetdatas()

public void setdatas(listdatas)

}

@component

private threadpoolexecutor threadpoolexecutor = new threadpoolexecutor(10, 20, 5l, timeunit.seconds, new linkedblockingqueue<>(20)); //執行緒池

private linkedblockingqueuerunnables = new linkedblockingqueue<>(10);//任務佇列

@override

ownermiddlequeryservice middlequeryservice = new ownermiddlequeryservice();

ownermiddledealservice middledealservice = new ownermiddledealservice();

for (int i = 0; i < 10; i++) catch (interruptedexception e)

}producer producer = new producer(middlequeryservice, runnables, threadpoolexecutor);

new thread(producer).start();//開啟生產者執行緒

}}

ownermiddledealservice  和 ownermiddlequeryservice的方法的實現都是些業務邏輯.主要邏輯已標明在注釋中.具體的邏輯則要根據系統的業務進行編碼.

具體可以參考:

併發並行同步非同步多執行緒

自 首先理解概念 你吃飯吃到一半,來了,你一直到吃完了以後才去接,這就說明你不支援併發也不支援並行。你吃飯吃到一半,來了,你停了下來接了 接完後繼續吃飯,這說明你支援併發。不一定是同時的 你吃飯吃到一半,來了,你一邊打 一邊吃飯,這說明你支援並行。併發的關鍵是你有處理多個任務的能力,不一定要同時。並...

Linux程式設計 執行緒互斥量進行同步

互斥量是乙個可以處於兩態之一的變數 解鎖和加鎖。為控制對關鍵 的訪問,必須在進入這段 之前鎖住乙個互斥量,然後在完成操作之後解鎖它。thread4.c include include include include include include void thread function void ...

唯快不破 多執行緒 使用訊號量進行同步

訊號量是最早出現的用來解決程序同步與互斥問題的機制 也可實現程序通訊 包括乙個稱為訊號量的變數及對它進行的兩個原語操作。訊號量為乙個整數,我們設這個訊號量為 sem。很顯然,我們規定在sem大於等於零的時候代表可供併發程序使用的資源實體數,sem小於零的時候,表示正在等待使用臨界區的程序的個數。根據...