class Exam1 {
public synchronized void methodThree() {
System.out.println("methodThree() begin:" + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format((new Date())));
long i = 0L;
while (i < 100000000000L) {
i++;
}
System.out.println(i);
System.out.println("methodThree() end:" + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format((new Date())));
}
public synchronized void methodFour() {
System.out.println("methodFour() begin");
System.out.println("methodFour() end");
}
}
public class Exam2 {
public static void main(String[] args) {
final Exam1 exam1 = new Exam1();
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
exam1.methodThree();
}
});
t3.start();
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
exam1.methodFour();
timer.cancel();
}
}, 50, 10);
}
}
代码如上所示,Exam1类有两个方法,methodThree( )和methodFour( ):
1、methodThree( )和methodFour( )都没有加synchronized关键字时,调用结果如下所示:
methodThree() begin:2019-05-01 21:22:45
methodFour() begin
methodFour() end
methodThree() end:2019-05-01 21:23:17
结论:调用methodThree( ),不影响methodFour( )的调用。
2、methodThree( )和methodFour( )都加synchronized关键字时,调用结果如下所示:
methodThree() begin:2019-05-01 21:36:28
methodThree() end:2019-05-01 21:37:00
methodFour() begin
methodFour() end
结论:必须按调用的顺序依次执行。
3、methodThree( )和methodFour( )只有其中一个加synchronized关键字时,调用结果如下所示:
methodThree() begin:2019-05-01 21:22:45
methodFour() begin
methodFour() end
methodThree() end:2019-05-01 21:23:17
结论:不加锁的那个方法不受影响。
static注意:
methodThree( )和methodFour( )都是static静态方法,且都加了synchronized关键字,创建不同的线程分别调用methodThree( )和methodFour( ),需要等methodThree( )执行完成才能执行methodFour( )(因为static方法是单实例的,methodThree( )持有的是Class锁,Class锁可以对类的所有对象实例起作用)
总结:
同一个object中多个方法都加了synchronized关键字的时候,其中调用任意方法之后需等该方法执行完成才能调用其他方法,即同步的,阻塞的;synchronized(this)同步代码块的场景也是如此。