class ClasseAttiva extends Thread{
    protected static int shared = 0;
    protected static Object lock = new Object();
    public void run() {
        while (true) {
            synchronized(lock){
                if (shared >= 10) break;
                try {
                    Thread.sleep(1000);
                }
                catch(InterruptedException e){
                    System.err.println(e);
                }
                if (shared >= 10){
                    throw new Error("Corsa critica!!!");
                }
                System.out.print(this.getName());
                System.out.print(" s = ");
                System.out.println(this.shared);
                shared += 1;
            }
            Thread.yield(); // non necessaria, ma favorisce lo scheduling di entrambi
        }
    }
}



public class Shared2 {
    public static final void main(final String[] args) {
        ClasseAttiva o1 = new ClasseAttiva();
        ClasseAttiva o2 = new ClasseAttiva();
        o1.start();
        o2.start();
        while (true){
            try {
                Thread.sleep(1000);
            }
            catch(InterruptedException e){
                System.err.println(e);
            }

            System.out.println("Main thread");
        }
        
    }
}



