1、修饰静态方法
public class SynchronizedDemo { public static int i=0; public synchronized static void accessResource() { try { i++; TimeUnit.SECONDS.sleep(2); System.out.println(Thread.currentThread().getName()+"is running:" + i); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) { for (int i=0;i<5;i++){ new Thread(SynchronizedDemo::accessResource).start(); } } }
2.修饰非静态方法:
public class SynchronizedDemo { public int i=0; public synchronized void accessResource() { try { i++; TimeUnit.SECONDS.sleep(2); System.out.println(Thread.currentThread().getName()+"is running:" + i); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) { SynchronizedDemo synchronizedDemo = new SynchronizedDemo(); for (int i=0;i<5;i++){ new Thread(synchronizedDemo::accessResource).start(); } } }