import java.util.concurrent.locks.*; import java.util.*; class Main { public static void main(String[] args){ Kode kode= new Kode(); Thread lunte= new Thread(new Bombespill(kode)); Thread def = new Thread(new Desarmer(kode)); lunte.start(); def.start(); try { def.join(); } catch (InterruptedException e){} lunte.interrupt(); } } class Bombespill implements Runnable { Kode kode; int i = 5; public Bombespill(Kode k){ System.out.println("Legg inn armeringskode: "); k.addCode(new Scanner(System.in).nextLine()); } @Override public void run(){ while (i>0){ System.out.println(i); i--; try { Thread.sleep(1000); } catch (InterruptedException e){return;} } System.out.println("BOOOM!"); System.exit(0); } } class Desarmer implements Runnable { Scanner sc = new Scanner(System.in); Kode kode; public Desarmer (Kode kode){ this.kode = kode; } @Override public void run(){ System.out.println("Skriv: " + kode.getCode() + " for aa desarmere bomben!\nBomben sprenger om 5 sekunder!"); String inn = sc.nextLine(); while (!kode.compareCode(inn)){ System.out.println("Feil input"); inn = sc.nextLine(); } System.out.println("Phew!"); } } class Kode{ private Lock lock = new ReentrantLock(); private String code; public boolean compareCode(String s){ return s.equals(code); } public void addCode(String c){ lock.lock(); try { code = c; } finally { lock.unlock(); } } public String getCode(){ return code; } }