PDA

View Full Version : [JAVA] Far partire più Servlet nello stesso momento


GennyAndroid
06-05-2014, 18:35
Siccome ho paura di essere frainteso ho realizzato un video che spiega il risultato che vorrei ottenere:

https://www.youtube.com/watch?v=PCi09ZvZ720&feature=youtu.be

La web application deve essere in grado di far girare le due Servlet contemporaneamente.

Ho realizzato due servlet identiche (Servlet1, Servlet2) che per 10 secondi stampano in console un messaggio:


import java.io.IOException;


import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;


@WebServlet("/Servlet1")
public class Servlet1 extends GenericServlet {
private static final long serialVersionUID = 1L;


public Servlet1() {
}

public void stampa(int n, String where){
for(int i = 0; i<=n; i++){
System.out.println(where+": "+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


@Override
public void init() throws ServletException {
super.init();
}

@Override
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
stampa(10, this.getClass()+" service");
}


}


Come si può evincere dal video, se chiamo le due Servlet il web container giustamente riesce ad eseguirle in contemporanea senza alcun problema.

Deve esserci un modo per riuscire ad ottenere lo stesso risultato da codice...:help:

Daniels118
13-05-2014, 16:00
Non riesco ad immaginare un buon motivo per fare una cosa del genere, comunque non c'è bisogno di una servlet, basta definire una classe che implementi l'interaccia Runnable e la esegui con il metodo start di un oggetto Thread:

Runnable r = new TuaClasse();
Thread t = new Thread();
t.start(r);

Se vuoi comunque lasciare il codice in una servlet, basta che nel metodo run della classe runnable crei una nuova istanza della servlet e ne chiami il metodo appropriato.