我想同時執行這兩段代碼。下面的代碼我到目前爲止:在Java中同時運行兩個任務
@Path("/cases")
public class CaseResource {
@GET
@Path("/getCaseNumber")
@Produces(MediaType.TEXT_PLAIN)
public String getNextCaseNumber(
@ApiParam(value = "tenant id", required = true)
@HeaderParam("tenant_id") String tenantId) throws Exception {
//Piece #1
String caseNum1 = new CaseHelper(new ConfigurationService(),new CaseService()).getNextCaseNumberFromDatabase(tenantId);
Case tempCase = new Case();
tempCase.setCaseStatusCode(new CodeService().getCodeForKeyGroup("ACTIVE","CASE_STATUS"));
caseService.saveCase(tempCase, tenantId);
//Piece #2
String caseNum2= new CaseHelper(new ConfigurationService(),new CaseService()).getNextCaseNumberFromDatabase(tenantId);
String caseNumbers = "{case1: " + caseNum1 + ", case2:" + caseNum2 + "}";
return caseNumbers;
}
}
一切都在這裏工作,但我想在同一時間做了以下工作:
任務1:輸出caseNum1,新的情況下保存到數據庫
任務2:輸出caseNum2
這裏就是我試圖做的:
@Path("/cases")
public class CaseResource {
String caseNum1;
String caseNum2;
@GET
@Path("/getCaseNumber")
@Produces(MediaType.TEXT_PLAIN)
public String getNextCaseNumber(
@ApiParam(value = "tenant id", required = true)
@HeaderParam("tenant_id") final String tenantId) throws Exception {
new Thread(new Runnable() {
public void run() {
caseNum1= new CaseHelper(new ConfigurationService(),new CaseService()).getNextCaseNumberFromDatabase(tenantId);
Case tempCase = new Case();
tempCase.setCaseStatusCode(new CodeService().getCodeForKeyGroup("ACTIVE","CASE_STATUS"));
caseService.saveCase(tempCase, tenantId);
}
}).start();
new Thread(new Runnable() {
public void run() {
caseNum2 = new CaseHelper(new ConfigurationService(),new CaseService()).getNextCaseNumberFromDatabase(tenantId);
}
}).start();
String caseNumbers = "{case1: " + caseNum1 + ", case2:" + caseNum2 + "}" ;
return caseNumbers;
}
}
但caseNum1和caseNum2返回null。任何想法爲什麼?也許run()沒有正確調用。雖然,我甚至不確定我是否正在執行此線程權限。有任何想法嗎?
對於以** **確切的時間看相同於[此](http://stackoverflow.com/questions/3376586/how-to-start-two-threads-at-exactly-啓動線程同一時間) – Dan
它看起來好像你要運行這個作爲一個Web服務。你可能想重新考慮使用實例變量,因爲你可能有多個併發請求 – user1675642