[英]Java create unique thread per database row
我有要求每x秒輪詢一次數據庫,並提取需要處理的記錄。 我將為每個這些行啟動一個線程。 下次我輪詢線程可能尚未完成。 我不想以相同的ID啟動另一個線程,因為它仍在處理中。
HashMap<String, Callable>
似乎適合存儲線程並確保每個ID僅存在一個線程。 我不知道是在線程完成后如何刪除線程?
我的理解是,如果我在線程上等待,那么它將阻塞主線程,並且輪詢將不會繼續。
我已經嘗試了以下代碼,並且可以正常工作,但是隨着更多任務的到來,HashMap將繼續增長。有可能在當天晚些時候對該行進行重新處理。
HashMap<String, Callable<String>> callables = new HashMap<String, Callable<String>>();
for(int i =0; i < 10; i++)
{
for(int j =0; j < 10; j++)
{
String key = Integer.toString(j);
if(!callables.containsKey(key))
{
callables.put(key, new Callable<String>() {
public String call() throws Exception {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Inside task");
return "Task Completed";
}
});
try
{
callables.get(key).call();
}
catch(Exception ex){
ex.printStackTrace();
}
}
else
System.out.println("Task skipped: " + j);
}
}
如果您的問題是在線程完成其工作后從地圖中移除夫婦(鍵,Callable)。 在其call()函數的末尾調用remove()。
HashMap<String, Callable<String>> callables = new HashMap<String,
Callable<String>>();
for(int i =0; i < 10; i++) {
for(int j =0; j < 10; j++) {
String key = Integer.toString(j);
if(!callables.containsKey(key)) {
callables.put(key, new Callable<String>() {
final String mKey = key; //store the current key
public String call() throws Exception {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Inside task");
callables.remove(mKey); //Remove the thread from the Map
return "Task Completed";
}
});
try {
callables.get(key).call();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
else
System.out.println("Task skipped: " + j);
}
}
您可以將Callable
包裝在您自己的Callable
。
HashMap<String, Callable<String>> callables = new HashMap<>();
public void oneOnly(String id, Callable<String> callable) {
if (!callables.containsKey(id)) {
// Wrap the callable in my own.
callables.put(id, new Callable<String>() {
public String call() throws Exception {
String result = callable.call();
// Remove when finished.
callables.remove(id);
return result;
}
});
}
}
public void test(String[] args) throws Exception {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
String key = Integer.toString(j);
oneOnly(key, new Callable<String>() {
public String call() throws Exception {
System.out.println("Inside task");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Task Completed";
}
});
try {
callables.get(key).call();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.