|
| 1 | +import java.time.LocalDateTime; |
| 2 | +import java.time.format.DateTimeFormatter; |
| 3 | +import java.util.concurrent.CountDownLatch; |
| 4 | + |
| 5 | +import static java.util.concurrent.TimeUnit.SECONDS; |
| 6 | + |
| 7 | +/** |
| 8 | + * #15 ASINCRONÍA |
| 9 | + * |
| 10 | + * @author martinbohorquez |
| 11 | + */ |
| 12 | +public class martinbohorquez { |
| 13 | + |
| 14 | + private static final DateTimeFormatter f = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss"); |
| 15 | + |
| 16 | + public static void main(String[] args) throws InterruptedException { |
| 17 | + CountDownLatch latch = new CountDownLatch(2); |
| 18 | + getTask("tarea 1", 3, latch); |
| 19 | + getTask("tarea 2", 2, latch); |
| 20 | + latch.await(); |
| 21 | + |
| 22 | + /* |
| 23 | + * DIFICULTAD EXTRA |
| 24 | + */ |
| 25 | + latch = new CountDownLatch(3); |
| 26 | + System.out.println("[======== DIFICULTAD EXTRA =========]"); |
| 27 | + getTask("C", 3, latch); |
| 28 | + getTask("B", 2, latch); |
| 29 | + getTask("A", 1, latch); |
| 30 | + latch.await(); |
| 31 | + getTask("D", 1, latch); |
| 32 | + |
| 33 | + } |
| 34 | + |
| 35 | + private static void getTask(String tarea, int duration, CountDownLatch latch) throws InterruptedException { |
| 36 | + Task task = new Task(tarea, duration, latch); |
| 37 | + task.start(); |
| 38 | +// if (join) task.join(); |
| 39 | + } |
| 40 | + |
| 41 | + public static class Task extends Thread { |
| 42 | + private final int duration; |
| 43 | + private final CountDownLatch latch; |
| 44 | + |
| 45 | + public Task(String name, int duration, CountDownLatch latch) { |
| 46 | + super(name); |
| 47 | + this.duration = duration; |
| 48 | + this.latch = latch; |
| 49 | + } |
| 50 | + |
| 51 | + @Override |
| 52 | + public void run() { |
| 53 | + System.out.printf("Tarea: %s | Duración: %d segundos | Inicio: %s%n", |
| 54 | + getName(), duration, LocalDateTime.now().format(f)); |
| 55 | + try { |
| 56 | + SECONDS.sleep(duration); |
| 57 | +// sleep(Duration.ofSeconds(duration)); |
| 58 | + } catch (InterruptedException e) { |
| 59 | + throw new RuntimeException(e); |
| 60 | + } |
| 61 | + System.out.printf("Tarea: %s | Fin: %s%n", getName(), LocalDateTime.now().format(f)); |
| 62 | + latch.countDown(); |
| 63 | + System.out.printf("El contador de %s es: %s%n", getName(), latch.getCount()); |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments