Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- */
- package exercicioprimos;
- import java.util.Timer;
- import java.util.TimerTask;
- public class Principal {
- public static int opcao = 2;
- public static int tempo = 5;
- private static class Task implements Runnable {
- private Timer timer = new Timer();
- volatile boolean finaliza = false;
- public static long ultimoPrimo = 3;
- public long contador = 1;
- @Override
- public void run() {
- System.out.println("INICIANDO");
- timer.schedule(new TimerTask() {
- @Override
- public void run() {
- finaliza = true;
- }
- }, tempo * 1000);
- while (!finaliza) {
- boolean ehPrimo = false;
- long numeral;
- synchronized (this) {
- numeral = ultimoPrimo + 2;
- }
- ehPrimo = verificaPrimo(numeral);
- if (ehPrimo) {
- System.out.println(Thread.currentThread().getName() + " achou " + (numeral));
- contador++;
- synchronized (this){
- ultimoPrimo = numeral;
- }
- }
- }
- System.out.println("final do loop da thread " + Thread.currentThread().getName());
- timer.cancel();
- }
- private boolean verificaPrimo(long numero) {
- int divisor = 2;
- double raiz = Math.sqrt(numero);
- while (divisor <= raiz) {
- if (numero % divisor == 0) {
- return false;
- }
- divisor++;
- }
- return true;
- }
- };
- public static void main(String[] args) throws InterruptedException {
- long contadorFinal;
- Task task1 = new Task();
- Task task2 = new Task();
- Task task3 = new Task();
- Task task4 = new Task();
- Thread t1 = new Thread(task1);
- Thread t2 = new Thread(task2);
- Thread t3 = new Thread(task3);
- Thread t4 = new Thread(task4);
- do {
- switch (opcao) {
- case 1:
- t1.start();
- Thread.sleep((tempo + 3) * 1000);
- contadorFinal = task1.contador;
- System.out.println(" Foram Encontrados " + contadorFinal + " primos!"
- + "\n O ultimo Primo Encontrado foi " + Task.ultimoPrimo);
- case 2:
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- Thread.sleep((tempo + 3) * 1000);
- contadorFinal = task1.contador + task2.contador + task3.contador + task4.contador;
- System.out.println(" Foram Encontrados " + contadorFinal + " primos!"
- + "\n O ultimo Primo Encontrado foi " + Task.ultimoPrimo);
- case 3:
- t1.start();
- Thread.sleep((tempo + 3) * 1000);
- contadorFinal = task1.contador;
- System.out.println(" Foram Encontrados " + contadorFinal + " primos!"
- + "\n O ultimo Primo Encontrado foi " + Task.ultimoPrimo);
- }
- } while (opcao != 0);
- //task.run(); sem threads
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement