title: Running two tasks at the same time in Java
body: <p>I want to execute these two pieces of code at the same time. Here's the code I have so far:</p>
  
  <pre><code>@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;
      }
  }
  </code></pre>
  
  <p>Everything works here, but I am wanting to do the following tasks at the same time:</p>
  
  <p><strong>Task1: Output caseNum1, save new case to database</strong></p>
  
  <p><strong>Task2: output caseNum2</strong></p>
  
  <p>Here's what I tried to do:</p>
  
  <pre><code>@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;
      }
  }
  </code></pre>
  
  <p>But caseNum1 and caseNum2 are returning null. Any idea why? Maybe run() is not being correctly called. Although, I am not even sure if I am doing this threading right. Any ideas?</p>