gpt4 book ai didi

java - Java同时运行两个任务

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:16:17 24 4
gpt4 key购买 nike

我想同时执行这两段代码。这是我到目前为止的代码:

@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;
}
}

这里一切正常,但我想同时执行以下任务:

Task1:输出caseNum1,将新case存入数据库

任务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() 没有被正确调用。虽然,我什至不确定我是否正确执行此线程。有什么想法吗?

最佳答案

试试这个:

    ...

CountDownLatch latch = new CountDownLatch(2);


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);
latch.countDown();
}
}).start();

new Thread(new Runnable() {
public void run() {
caseNum2 = new CaseHelper(new ConfigurationService(),new CaseService()).getNextCaseNumberFromDatabase(tenantId);
latch.countDown();

}
}).start();

latch.await();

...

关于java - Java同时运行两个任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34906220/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com