Fala ae pessoal. Tudo beleza com vocês?
Resolvi testar se havia alguma diferença entre as classes Callable e o Runnable para executar Threads e aqui para mim o Callable não está funcionando em paralelismo, já o Runnable sim. Poderiam me explicar, e exemplificar o porque disso. Se eu estiver fazendo algo de errado me corrijam, por favor.
Seguem ae as minhas classes.
Classe Principal
package br.com.exemplo.thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TesteExceptionThread {
public static void main(String[] args) {
try {
ExemploCallable ec = new ExemploCallable(99);
ExemploCallable ec2 = new ExemploCallable(11);
ExecutorService thread = Executors.newSingleThreadExecutor();
ExecutorService thread2 = Executors.newSingleThreadExecutor();
Integer result = thread.submit(ec).get();
result = thread2.submit(ec2).get();
System.out.println("\n ");
ExemploRunnable er = new ExemploRunnable(22);
ExemploRunnable er2 = new ExemploRunnable(11);
Thread t = new Thread(er);
Thread t2 = new Thread(er2);
t.start();
t2.start();
}
catch (NumberFormatException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Classe Callable
package br.com.exemplo.thread;
import java.util.concurrent.Callable;
public class ExemploCallable implements Callable<Integer> {
private Integer numero;
public ExemploCallable(Integer numero) {
this.numero = numero;
}
@Override
public Integer call() throws Exception {
for(int x = 0; x<=numero; x++) {
System.out.println(" ===> CALLABLE NUMERO " + numero + " X: " + x + " ");
}
return 0;
}
}
Classe Runnable
package br.com.exemplo.thread;
public class ExemploRunnable implements Runnable {
private Integer numero;
public ExemploRunnable(Integer numero) {
this.numero = numero;
}
@Override
public void run() {
for(int x = 0; x<=numero; x++) {
System.out.println(" ===> RUNNABLE NUMERO " + numero + " X: " + x + " ");
}
}
}
Grande Abraço.
