I metodi synchronized in Java
I metodi synchronized sono utilizzati per fornire un meccanismo di sincronizzazione riguardante i metodi.
La definizione di un metodo sincronizzato avviene utilizzando la parola chiave synchronized nella sua dichiarazione:
public static class Sync { public synchronized void f() { System.out.println("Sync.f()"); } }
Quando un thread richiama il metodo synchronized su un oggetto, tutti gli altri thread che richiamano quel metodo dopo sospendono la loro esecuzione fino a che non termina l’esecuzione del metodo (richiamato dal primo thread).
In questo esempio:
public class Main { public static class Sync { public synchronized void f() { try { Thread.sleep(1000); System.out.println("Sync.f()"); Thread.sleep(1000); } catch(InterruptedException e) { System.out.println(e); } } } static Sync sync = new Sync(); public static class MyThread implements Runnable { public void run() { System.out.println( Thread.currentThread().getName() + " inizia"); sync.f(); System.out.println( Thread.currentThread().getName() + " termina"); } } public static void main(String[] argv) { Thread[] threads = new Thread[3]; for(int i = 0; i < threads.length; i++) { threads[i] = new Thread( new MyThread() ); threads[i].start(); } for(int i = 0; i < threads.length; i++) { try { threads[i].join(); } catch(InterruptedException e) { System.out.println(e); } } } }
ogni thread attenderà la terminazione della chiamata del metodo synchronized effettuata dal thread che lo precede nel tempo.