/** * Falls sich ein Thread im synchronisierten Block * synchronized (this) { ... } * befindet, welche anderen Methoden werden dann für andere Threads "gesperrt"? * Statische Methoden werden nicht gesperrt. Methoden, die selbst nicht * synchronized im Methodenkopf haben, werden ebenfalls nicht gesperrt. Nur * Membermethoden (non-static), die synchronized im Methodenkopf enthalten, * werden gesperrt, bzw. blockiert. */ public class ThisSynchDemo { public static void main(String[] args) { final ThisSynchDemo t = new ThisSynchDemo(); new Thread() { public void run() { t.lockMethod(); } }.start(); sleep(100); // Warten, bis das this sicher gesperrt ist /* * Starte die verschiedenen Methoden und schaue, welche sich melden. Die * anderen sind blockiert, weil über das this synchronisiert wurde. */ new Thread() { public void run() { t.nonstatic_nonsync_method(); } }.start(); new Thread() { public void run() { t.nonstatic_sync_method(); } }.start(); new Thread() { public void run() { static_nonsync_method(); } }.start(); new Thread() { public void run() { static_sync_method(); } }.start(); } private void lockMethod() { synchronized (this) { System.out.println("this ist gesperrt"); while(true) { sleep(1000); } } } private void nonstatic_nonsync_method() { keepPrinting("Non-static, nicht synchronisiert"); } private synchronized void nonstatic_sync_method() { keepPrinting("Non-static, aber synchronisiert"); } private static void static_nonsync_method() { keepPrinting("static, nicht synchronisiert"); } private static synchronized void static_sync_method() { keepPrinting("static und synchronisiert"); } private static void keepPrinting(String s) { while(true) { System.out.println(s); sleep(1000); } } private static void sleep(long time) { try { Thread.sleep(time); } catch (InterruptedException e) { e.printStackTrace(); } } }