Estoy tratando de realizar lo que hay dentro de la condición while, pero cuando la condición finaliza, los subprocesos continúan verificando la salida. Necesito detener lo que hay dentro del ciclo while de acuerdo con el temporizador, básicamente haciendo el trabajo del temporizador.
public static long start = System.currentTimeMillis(); public static long end = start + 10 * 1000; // 10 seconds * 1000 ms/sec while (System.currentTimeMillis() <= end) { Thread t = new Thread(new UserGenerator()); Thread t1 = new Thread(new Vote()); t.start(); Thread.sleep(1000); t1.start(); Thread.sleep(1000); } System.err.println("Time Done");producción
Name:Alaine,Email:lg@shapirosher.com ,SSN:516517 Name:Adriana,Email:donbenchoff@comcast.net ,SSN:526527 Time Done User 516517 Voted User 526527 Voted BUILD SUCCESSFUL (total time: 16 seconds)Esto es lo que hace el código anterior:
UserGenerator y un hilo de Vote por segundo Entonces, después de 10 segundos, el ciclo while terminará y el hilo main saldrá. Sin embargo, 5 threds iniciados por él continuarán ejecutándose (hasta que finalice su método de run o se produzca una excepción). Depende de cómo run implemente el método de ejecución en las clases UserGenerator y Vote . Por ejemplo, si hay un ciclo infinito, esos subprocesos continuarán ejecutándose y el programa nunca se cerrará.
No estoy seguro de tener suficiente información para una respuesta completa, sin embargo, puede intentar esto:
long start = System.currentTimeMillis(); long end = start + (10 * 1000); // 10 seconds * 1000 ms/sec List<UserGenerator> us = new ArrayList<>(); List<Vote> vs = new ArrayList<>(); Thread t, t1; while (System.currentTimeMillis() <= end) { UserGenerator u; Vote v; t = new Thread( u = new UserGenerator()); t1 = new Thread(v = new Vote()); t.start(); us.add(u); if(end - System.currentTimeMillis() >= 1000) Thread.sleep(1000); t1.start(); vs.add(v); if(end - System.currentTimeMillis() >= 1000) Thread.sleep(1000); } t.interrupt(); t1.interrupt(); //the following may be redundant. It depends in what // UserGenerator and Vote do for(int i =0; i < us.ssize() ; i++) { us.get(i).stop(); vs.get(i).stop(); } System.err.println("Time Done"); } long start = System.currentTimeMillis(); long end = start + (10 * 1000); // 10 seconds * 1000 ms/sec List<UserGenerator> us = new ArrayList<>(); List<Vote> vs = new ArrayList<>(); Thread t, t1; while (System.currentTimeMillis() <= end) { UserGenerator u; Vote v; t = new Thread( u = new UserGenerator()); t1 = new Thread(v = new Vote()); t.start(); us.add(u); if(end - System.currentTimeMillis() >= 1000) Thread.sleep(1000); t1.start(); vs.add(v); if(end - System.currentTimeMillis() >= 1000) Thread.sleep(1000); } t.interrupt(); t1.interrupt(); //the following may be redundant. It depends in what // UserGenerator and Vote do for(int i =0; i < us.ssize() ; i++) { us.get(i).stop(); vs.get(i).stop(); } System.err.println("Time Done"); }