Possibility to schedule threads in Java to run at different times

Asked

Viewed 997 times

3

I have a system multithreading which is the same as the topic post link - Java Thread Sync (sync collections) in Java that allows scheduling threads to perform at different times.

That way, the class agendarTarefa receives the hour and minute of class Relogio to create a new task Thread and threadRelogio to execute the threads.

Class Relogio containing hour and minute:

public class Relogio {

    private int horas;
    private int minutos;

    public Relogio() {
        this.horas = 0;
        this.minutos = 0;
    }

    public Relogio(int hora, int minuto) {
        this.horas = hora;
        this.minutos = minuto;
    } 
}

Class Tarefa which receives the time and minute of a clock and creates a schedule:

public class AgendarTarefa {

    private Relogio relogio;
    private boolean estado;


    public AgendarTarefa(Relogio relogioAgenda) {
        this.relogio = relogioAgenda;
    }
}

Class ThreadRelogio to run threads until finished:

public class ThreadRelogio extends Thread {

    private final Object mutex = new Object();

    private boolean parou = false;
    private int tempo = 0;

    @Override
    public void run() {
        try {
            while (!parou) {
                Thread.sleep(1000);
                synchronized (mutex) {
                    tempo++;
                    mutex.notifyAll();
                }
            }
        } catch (InterruptedException e) {
            // Ignora.
        }
    }
}

My doubt is when is created the threadAviao1 to run after a while the program must execute the other threadAviao2 knowing that the threadAviao1 not yet finished, for this to happen it is necessary to develop a method to advance clock or there is another solution?

I have an example of a 3 aircraft configuration to test the threads:

--- Avião ---  
Nº de Voo              : 1   
Origem                 : VENEZA  
Hora de Chegada ao IM  : 10:20  

--- Avião --- 
Nº de Voo              : 2  
Origem                 : DUBAI  
Hora de Chegada ao IM  : 10:30  

--- Avião ---  
Nº de Voo              : 3  
Origem                 : BRAZIL  
Hora de Chegada ao IM  : 10:40

From what I understand every 10 seconds this method is executed executarEtapa(Aeroporto aeroporto, Aviao aviao) Source of the code

public void executarEtapa(Aeroporto aeroporto, Aviao aviao) {
         //contador
         int contador = 0;
        //por enquanto a cada aviao executar uma 
        //etapa sai de executa a etapa de outro aviao
        while (contador != 1) {
            aeroporto.AviaoChegou(aviao);
            //aguardar um tempo
            aeroporto.getRelogio().esperar();
            //aviao partiu
            aeroporto.AviaoPartiu(aviao);
            //incrementa contador
            contador++;
        }
    }

Class ThreadAviao to perform the aeroplane stages:

public class ThreadAviao extends Thread {

        private final Aviao aviao;
        private final Aeroporto aeroporto;

        public ThreadAviao(Aeroporto aeroporto, Aviao aviao) {
            this.aviao = aviao;
            this.aeroporto = aeroporto;
        }

        @Override
        public void run() {
            try {
                synchronized (mutex) {
                    while (!comecou) {
                        mutex.wait();
                    }
                List<Aviao> lista = new ArrayList<>();
                //adiciona o aviao a lista
                lista.add(aviao);
                //ordena os avioes
                Collections.sort(lista);
                //escolhe um aviao 
                for (Aviao novoAviao: lista) {
                    //inicia a etapa
                    etapaAviao.executarEtapa(aeroporto, novoAviao);
                }
               }
            } catch (InterruptedException e) {
                // Não faz nada.
            }
        }
    }

Any suggestions?

2 answers

2

There are several answers on how to handle timers in Java:

In this particular case it seems appropriate to me to use a Timer to schedule the execution of a task at a given time using the method schedule(TimerTask, Date).

Through the hour and minute, you will need to build an object Date. Then create a TimerTask that notifies or starts the thread you want to run at the given time.

I did not make a more concrete example because it was not clear to me in the question what exactly the behavior of the system, that is, whether it will work in real time or whether it will advance time artificially, or even if the scheduling occurs only once or if it repeats every day, because depending on this, the correct one could be using a date and not just the time.

  • thank you and your reply is very interesting, in fact it is just a simulation of some threads plane with scheduled arrival time and departure time, so the prof told us is that we have to schedule that the plane 1 thread arrives (starts thread) at 10:20 and part (finishes thread) at 10:30, only we do not know yet we will use the system time or not?

  • I will follow your reasoning to resolve and the Timer seems to be the most suitable and as it comes to Threads could also use ScheduledExecutorService ?

  • by which I understood every 10 seconds a Thread, that is, each iterated aviary of the collection runs after 10 seconds to start its task,(get->land->leave)

1

  • I don’t think a framework is necessary or desired for a system that is probably academic and is using pure Java.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.