synchronized同步语句块
用关键字synchronized声明方法是有弊端的。比如线程A调用同步方法执行一个长时间任务,那么线程B就要等较长时间才能调用。
下面看一个例子:
1 | public class Task { |
1 | public class Utils { |
1 | public class MyThread extends Thread{ |
1 | public class Main { |
输出内容:
1 | begin task |
从运行时间上来看,synchronized方法的问题很明显。可以使用synchronized同步块来解决这个问题。但是要注意synchronized同步块的使用方式,如果synchronized同步块使用不好的话并不会带来效率的提升。
将上文的Task.class文件修改如下:
1 | public void longTimeTask(){ |
输出如下:
1 | begin task |
从上面代码可以看出当一个线程访问一个对象的synchronized同步代码块时,另一个线程任然可以访问该对象非synchronized同步代码块。不在synchronized块中的就是异步执行,在synchronized块中就是同步执行。
synchronized代码块之间的同步性
当一个线程访问一个对象的synchronized(this)同步代码块时,其他线程对同一个object中的其他synchronized(this)同步代码块访问将被阻塞。
如果在一个类中有很多个synchronized方法,这是虽然能实现同步,但会受到阻塞。如果使用同步代码块锁非this对象,则synchronized(非this)代码块中的程序与同步方法是异步的,不与其他this同步方法争抢this锁。
静态同步synchronized方法与synchronized(class)代码块
关键字synchronized还可以在static方法是使用,是对当前的*.java文件的Class类进行加锁。非静态的synchronized关键字是给对象加锁。
1 | public static void printA() { |
1 | public class Main { |
输出内容:
1 | 线程名称为:A在1552262297299进入printA |
从运行结果可以看出:静态同步synchronized方法与synchronized(class)代码块持有的锁一样,都是Class锁,Class锁对对象的所有实例起作用。synchronized关键字加到非static静态方法上持有的是对象锁。线程A,B和线程C持有的锁不一样,所以A和B运行同步,但是和C运行不同步。
数据类型String的常量池特性
JVM具有String常量池缓存的功能,将synchronized(string)与String联合使用时会出现一些问题。
1 | String s1 = "a"; |
比如两个同步方法都是synchronized(“abc”){}那么多线程会持有相同的锁,所以大多数同步代码块不用String作为锁。
本文代码:GitHub
欢迎关注公众号: