import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Main { public static void main(String[] args) { TellerBeholder teller = new TellerBeholder(); Runnable task = new MyTask(teller); Thread worker1 = new Thread(task); Thread worker2 = new Thread(task); worker1.start(); worker2.start(); try { worker1.join(); worker2.join(); } catch (InterruptedException e) { System.out.println("Traad ble avbrutt"); return; } System.out.println("Alt er ferdig"); } } class MyTask implements Runnable { private TellerBeholder teller; public MyTask(TellerBeholder teller) { this.teller = teller; } public void run() { System.out.println("Starting! Shared counter = " + teller.hentTeller()); for (int i = 0; i < 10000; i++) { teller.oekTeller(); } System.out.println("Done! Shared counter = " + teller.hentTeller()); } } class TellerBeholder { private Lock laas = new ReentrantLock(); private int sharedCounter = 0; public void oekTeller() { laas.lock(); try { sharedCounter += 1; } finally { laas.unlock(); } } public int hentTeller() { return sharedCounter; } }