Después de iniciar el objeto hilo
thread1.start(); thread2.start();
necesito esperar la finalización de ambos hilos usando el método join () (la forma más común).
Me gusta esto.
try { thread1.join(); thread2.join(); } catch (InterruptedException e) { e.printStackTrace(); }
Todo el tutorial que veo usa algún método incorporado para la finalización de los hilos.
¿Hay alguna forma de esperar a que finalice el subproceso sin utilizar ningún método incorporado como join o ejecutor?
Cada hilo tiene un estado. NUEVO, EJECUTABLE, BLOQUEADO, EN ESPERA, TIMED_WAITING o TERMINADO
TERMINADO es un estado en el que puede buscar cada subproceso con el método thread.getState()
, que es el estado del subproceso una vez que finaliza la ejecución
// 2 Thread Object Thread threads[] = new Thread[2]; // store Thread Statuses Thread.State status[] = new Thread.State[2];
Dado que todos los subprocesos tienen estado. Antes de iniciar hilo almacenar su estado
for (int i = 0; i < 2; i++) { status[i] = threads[i].getState(); }
Una vez que inicia el subproceso El subproceso terminado tiene un estado de Terminado, puede usarlo y escribir su propio cheque para la finalización.
// custom way for finalization of the threads boolean finish = false; // initially all non finised while(!finish) { for (int i = 0; i < 2; i++) { if (threads[i].getState() != status[i]) { status[i] = threads[i].getState(); } } finish = true; for (int i = 0; i < 2; i++) { finish = finish && (threads[i].getState() == State.TERMINATED); } }