|
| 1 | +import java.time.LocalDateTime; |
| 2 | +import java.util.concurrent.ExecutorService; |
| 3 | +import java.util.concurrent.Executors; |
| 4 | + |
| 5 | +public class danhingar { |
| 6 | + |
| 7 | + public static void main(String[] args) throws InterruptedException { |
| 8 | + Thread thread = taskThread("1", 10); |
| 9 | + thread.start(); |
| 10 | + taskExecutor("1", 10); |
| 11 | + |
| 12 | + // Ejercicio extra |
| 13 | + extraThread(); |
| 14 | + |
| 15 | + } |
| 16 | + |
| 17 | + private static Thread taskThread(String name, int seconds) { |
| 18 | + return new Thread(() -> { |
| 19 | + try { |
| 20 | + System.out.println("Tarea: " + name + ". Duración: " + seconds + "s. Inicio: " + LocalDateTime.now()); |
| 21 | + Thread.sleep(seconds * 1000); |
| 22 | + System.out.println("Tarea: " + name + ". Fin: " + LocalDateTime.now()); |
| 23 | + } catch (InterruptedException e) { |
| 24 | + e.printStackTrace(); |
| 25 | + } |
| 26 | + }); |
| 27 | + } |
| 28 | + |
| 29 | + private static void taskExecutor(String name, int seconds) { |
| 30 | + ExecutorService threadpool = Executors.newCachedThreadPool(); |
| 31 | + threadpool.submit(() -> { |
| 32 | + System.out.println("Tarea: " + name + ". Duración: " + seconds + "s. Inicio: " + LocalDateTime.now()); |
| 33 | + try { |
| 34 | + Thread.sleep(seconds * 1000); |
| 35 | + } catch (InterruptedException e) { |
| 36 | + e.printStackTrace(); |
| 37 | + } |
| 38 | + System.out.println("Tarea: " + name + ". Fin: " + LocalDateTime.now()); |
| 39 | + }); |
| 40 | + threadpool.shutdown(); |
| 41 | + } |
| 42 | + |
| 43 | + private static void extraThread() { |
| 44 | + Thread threadC = taskThread("C", 3); |
| 45 | + Thread threadB = taskThread("B", 2); |
| 46 | + Thread threadA = taskThread("A", 1); |
| 47 | + |
| 48 | + threadC.start(); |
| 49 | + threadB.start(); |
| 50 | + threadA.start(); |
| 51 | + |
| 52 | + try { |
| 53 | + threadC.join(); |
| 54 | + threadB.join(); |
| 55 | + threadA.join(); |
| 56 | + } catch (Exception e) { |
| 57 | + System.out.println("Error al terminar la ejecución"); |
| 58 | + } |
| 59 | + |
| 60 | + Thread threadD = taskThread("D", 1); |
| 61 | + threadD.start(); |
| 62 | + } |
| 63 | +} |
0 commit comments