Advertisement
Guest User

Untitled

a guest
Oct 24th, 2014
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. public class Ejer2 {
  2.  
  3. // Muestra un mensaje precedido por el nombre del hilo
  4. private static void println(String message) {
  5. String threadName = Thread.currentThread().getName();
  6. System.out.println(threadName + ":" + message);
  7. }
  8.  
  9. private static void mensajes() {
  10. String mensajes[] = { "La vida es bella", "O no...", "Los pajaritos cantan",
  11. "Y molestan..." };
  12. try {
  13. for (int i = 0; i < mensajes.length; i++) {
  14. Thread.sleep(1000);
  15. println(mensajes[i]);
  16. }
  17. } catch (InterruptedException e) {
  18. println("Se acabó!");
  19. }
  20. }
  21.  
  22. public static void main(String args[]) throws InterruptedException {
  23.  
  24. println("Inicio del hilo de mensajes");
  25. Thread t = new Thread(()->{
  26. mensajes();
  27. },"Mensajes");
  28. t.start();
  29.  
  30. long horaInicio = System.currentTimeMillis();
  31. println("Esperando hasta que el hilo termine");
  32.  
  33. // Esperar hasta que el hilo termine
  34. while (t.isAlive()) {
  35.  
  36. println("Todavía esperando...");
  37. // Esperar como máximo 1 second para ver si ha terminado el hilo
  38. t.join(1000);
  39.  
  40. long tiempoEspera = System.currentTimeMillis() - horaInicio;
  41.  
  42. if (tiempoEspera > 5000 && t.isAlive()) {
  43. println("Cansado de esperar!");
  44. t.interrupt();
  45.  
  46. // Esperamos indefinidamente porque no debería tardar en
  47. // finalizar después de la interrupción
  48. t.join();
  49. }
  50. }
  51.  
  52. println("Por fin!");
  53. }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement