REST API + Java Multithreaded

2019-04-17 14:02发布

问题:

I managed to build a small REST API using eclipse. The following code works:

@Path("Info")
public class Rest {

@POST
@Path("/stats/{j}") 
@Produces("application/json")
public Response Status(@PathParam("j") String j) throws JSONException{
  JSONObject jsonObject = new JSONObject();
   String status = j;
   .
   .
 return Response.status(200).entity(result).build();
}
}

Could you advise me on how make this a multithreaded? I have an idea of what is multithreaded but I need some input on how to go about creating this code as multithreaded. was thinking of creating another class that implements Runnable:

class Demo implements Runnable {
  .
  .

}

Then, in my function Status(@PathParam("j") String j), I create an object of class Demo, For example:

public Response Status(@PathParam("j") String j) throws JSONException{
    Demo newThread = new Demo();
    JSONObject jsonObject = new JSONObject();
   String status = j;
   .
   .
 return Response.status(200).entity(result).build();
}
}

Thank you in advance!

回答1:

It already is multithreaded.

When deploying the application into an application server such as Jetty or Tomcat the thread pool of the application determines how many threads will be used to serve web request. Every time a user makes a new web request against your controller method, one of the available threads from the application server threadpool will be used.