I have a multithreading
system that is the same as the post link - Java Thread Synchronization (synchronize collections) in Java that allows you to schedule threads
to run at different times.
In this way, the agendarTarefa
class receives the hour and minute of the Relogio
class to create a new task Thread
and threadRelogio
to execute threads
.
Class Relogio
that contains 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
that receives the hour 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 execute threads until done:
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 threadAviao1
is created to execute after a while the program should execute the other threadAviao2
knowing that threadAviao1
has not yet finished, for this to happen it is necessary to develop a method to advance clock or is there another solution?
I have an example of a configuration of 3 airplanes 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
So I realized every 10 seconds this method is executed executarEtapa(Aeroporto aeroporto, Aviao aviao)
Source 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 airplane steps:
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?