import java.util.concurrent.locks.*; import java.util.Scanner; class Bang { public static void main(String[] args){ Kode kode = new Kode(); Thread lunte = new Thread(new Bombe(kode)); Thread desarmer = new Thread(new Desarmer(kode)); lunte.start(); desarmer.start(); try { desarmer.join(); } catch (InterruptedException e){}; lunte.interrupt(); } } class Bombe implements Runnable { Kode kode; int counter = 5; public Bombe (Kode k){ System.out.println("Legg inn armeringskode: "); k.lagreKode(new Scanner(System.in).nextLine()); } @Override public void run(){ while (counter > 0){ System.out.println(counter); counter--; 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 k){ kode = k; } @Override public void run(){ System.out.println("Skriv: " + kode.hentKode() + " for aa desarmere bomben!\nBomben sprenger om 5 sekunder!"); String inn = sc.nextLine(); while(!kode.sammenlignKode(inn)){ System.out.println("Feil input!"); inn = sc.nextLine(); } System.out.println("Phew!"); } } class Kode { Lock laas = new ReentrantLock(); private String kode; public boolean sammenlignKode(String k){ return k.equals(kode); } public void lagreKode(String k){ laas.lock(); try { kode = k; } finally { laas.unlock(); } } public String hentKode(){ return kode; } }