1、代码块(锁括号内的对象)
-
Object o = new Object(); synchronized (o){ }
2、实例方法 (this)
public synchronized void methods02(){
System.out.println("methods02");
}
3、静态方法(类对象)
public static synchronized void methods02(){
System.out.println("methods02");
}
区别:
1、有ab两个线程,请问先打印methods01还是methods02 (methods01)
资源类
static class Test{ public synchronized void methods01(){ System.out.println("methods01"); } public synchronized void methods02(){ System.out.println("methods02"); } }
结果说明:methods01先调用,先执行。
2、methods01方法中加入暂停3秒钟,请问先打印methods01还是methods02 (methods02)
static class Test{ public synchronized void methods01(){ try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("methods01"); } public synchronized void methods02(){ System.out.println("methods02"); } }
结果说明:两个方法调用同一个锁,即锁的this,被methods01抢夺后,methods02进入等待
3、添加一个普通的hello方法,请问先打印methods01还是hello (hello)
static class Test{ public synchronized void methods01(){ try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("methods01"); } public synchronized void methods02(){ System.out.println("methods02"); } public void hello(){ System.out.println("hello"); } }
hello没加锁不用等待methods01执行完
4、有两个实例对象,请问先打印methods01还是methods02 (methods02)
两个方法methods01锁住test实例对象,methods02锁住test02对象,methods02没有sleep先打印
5、有两个静态同步方法,有1个实例,请问先打印methods01还是methods02 (methods01)
static class Test{ public static synchronized void methods01(){ try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("methods01"); } public static synchronized void methods02(){ System.out.println("methods02"); } public void hello(){ System.out.println("hello"); } }
static锁住类对象,只有一个,需要等待methods01执行完。
6、有两个静态同步方法,有2部手机,请问先打印methods01还是methods02(methods01) 原因和5一样
7、有1个静态同步方法,有1个普通同步方法,有1个实例,请问先打印methods01还是methods02
static class Test{ public static synchronized void methods01(){ try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("methods01"); } public synchronized void methods02(){ System.out.println("methods02"); } public void hello(){ System.out.println("hello"); } }
methods01拿类锁,methods02拿对象锁,methods02不用等待
8、有1个静态同步方法,有1个普通同步方法,有2个实例,请问先打印methods01还是methods02
原因同7