package es.upm.dit.adsw.tema3; public class Livelock { private static final boolean left = false; private static final boolean right = true; public static void main(String[] args) throws InterruptedException { Pedestrian pedestrian1 = new Pedestrian("A", left); Pedestrian pedestrian2 = new Pedestrian("B", left); pedestrian1.setOther(pedestrian2); pedestrian2.setOther(pedestrian1); Thread thread1 = new Thread(pedestrian1); Thread thread2 = new Thread(pedestrian2); thread1.start(); thread2.start(); } } class Pedestrian implements Runnable { private final String id; private boolean current; private Pedestrian other; Pedestrian(String id, boolean lane) { this.id = id; current = lane; } void setOther(Pedestrian pedestrian) { other = pedestrian; } boolean getLane() { return current; } void switchDirection() { nap(1000); current = !current; System.out.println(id + " is stepping " + (current ? "right" : "left")); } public void run() { nap(1000); while (getLane() == other.getLane()) { switchDirection(); nap(1000); } } private void nap(int ms) { try { Thread.sleep(ms); } catch (InterruptedException ignored) { } } }