Entendendo o Java ExecutorService
Estou tentando aprender como usar o serviço executor de Java,
Eu estava lendo a seguinte discussãoFila simples de encadeamento Java
Neste, há um exemplo de exemplo
ExecutorService service = Executors.newFixedThreadPool(10);
// now submit our jobs
service.submit(new Runnable() {
public void run() {
do_some_work();
}
});
// you can submit any number of jobs and the 10 threads will work on them
// in order
...
// when no more to submit, call shutdown
service.shutdown();
// now wait for the jobs to finish
service.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
Eu tentei implementar esta solução, para isso eu criei um formulário e coloquei o botão iniciar e parar, mas o problema que estou enfrentando é que, se eu chamar esse processo no botão iniciar, ele travará o formulário completo e precisamos esperar até todo o processo está completo.
Eu também tentei ler o seguintehttps://www3.ntu.edu.sg/home/ehchua/programming/java/J5e_multithreading.html
mas até agora não sou capaz de entender como fazê-lo funcionar, pois depois de clicar no botão Iniciar, devo ter acesso novamente, supondo que queira interromper o processo.
alguém pode me guiar na direção certa.
obrigado
Para tornar minha situação mais clara, estou adicionando o código que estou testando.
Problemas
1) o formulário completo permanece congelado quando o programa é executado. 2) A barra de progresso não funciona, exibirá o status somente quando todo o processo estiver concluído.
private void btnStartActionPerformed(java.awt.event.ActionEvent evt) {
TestConneciton();
}
private void btnStopActionPerformed(java.awt.event.ActionEvent evt) {
flgStop = true;
}
private static final int MYTHREADS = 30;
private boolean flgStop = false;
public void TestConneciton() {
ExecutorService executor = Executors.newFixedThreadPool(MYTHREADS);
String[] hostList = { "http://crunchify.com", "http://yahoo.com",
"http://www.ebay.com", "http://google.com",
"http://www.example.co", "https://paypal.com",
"http://bing.com/", "http://techcrunch.com/",
"http://mashable.com/", "http://thenextweb.com/",
"http://wordpress.com/", "http://wordpress.org/",
"http://example.com/", "http://sjsu.edu/",
"http://ebay.co.uk/", "http://google.co.uk/",
"http://www.wikipedia.org/",
"http://en.wikipedia.org/wiki/Main_Page" };
pbarStatus.setMaximum(hostList.length-1);
pbarStatus.setValue(0);
for (int i = 0; i < hostList.length; i++) {
String url = hostList[i];
Runnable worker = new MyRunnable(url);
executor.execute(worker);
}
executor.shutdown();
// Wait until all threads are finish
// while (!executor.isTerminated()) {
//
// }
System.out.println("\nFinished all threads");
}
public class MyRunnable implements Runnable {
private final String url;
MyRunnable(String url) {
this.url = url;
}
@Override
public void run() {
String result = "";
int code = 200;
try {
if(flgStop == true)
{
//Stop thread execution
}
URL siteURL = new URL(url);
HttpURLConnection connection = (HttpURLConnection) siteURL
.openConnection();
connection.setRequestMethod("GET");
connection.connect();
code = connection.getResponseCode();
pbarStatus.setValue(pbarStatus.getValue()+1);
if (code == 200) {
result = "Green\t";
}
} catch (Exception e) {
result = "->Red<-\t";
}
System.out.println(url + "\t\tStatus:" + result);
}
}