/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package synktest2; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author karlssoj */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic he new Kora(); } } class Kora implements Runnable { Synkroniserad s = new Synkroniserad(); public Kora() { new Thread(this).start(); while(true) { s.inkrement(); } } public void run() { //tråd2 while(true) { s.visa(); try { Thread.sleep(200); } catch (InterruptedException ex) {} } } } class Synkroniserad { int tal, tal2; //vi vill synkronisera åtkomst av inkrement metoden och visa metdoen //men vi vill inte att de ska vara beroende av varandra, vi vill m.a.o. //att de ska ha skilda lås void inkrement() { Object las1 = new Object(); synchronized(las1) { tal++; try { Thread.sleep(1000); } catch (InterruptedException ex) {} } } void visa() { Object las2 = new Object(); synchronized(las2) { System.out.println("Talet är: " + tal); } } }