Java多线程学习(三)——synchronized(下)

249 阅读4分钟

synchronized同步语句块

用关键字synchronized声明方法是有弊端的。比如线程A调用同步方法执行一个长时间任务,那么线程B就要等较长时间才能调用。

下面看一个例子:

public class Task {

    private String getData1;

    private String getData2;

    public synchronized void longTimeTask(){
        try {
            System.out.println("begin task");
            Thread.sleep(3000);
            getData1 = "长时间处理任务后从远程返回的值1 threadName=" + Thread.currentThread().getName();
            getData2 = "长时间处理任务后从远程返回的值2 threadName=" + Thread.currentThread().getName();
            System.out.println(getData1);
            System.out.println(getData2);
            System.out.println("end task");
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }

}
public class Utils {
    public static long begainTime1;
    public static long endTime1;
    public static long begainTime2;
    public static long endTime2;


}
public class MyThread extends Thread{
    private Task task;
    private String name;

    public MyThread(Task task, String name){
        super();
        this.task=task;
        this.name=name;
        super.setName(name);
    }

    @Override
    public void run() {
        super.run();
        if ("A".equals(name)){
            Utils.begainTime1 = System.currentTimeMillis();
            task.longTimeTask();
            Utils.endTime1 = System.currentTimeMillis();
        }else {
            Utils.begainTime2 = System.currentTimeMillis();
            task.longTimeTask();
            Utils.endTime2 = System.currentTimeMillis();
        }
    }
}
public class Main {
    public static void main(String[] args){
        Task task = new Task();
        MyThread myThread = new MyThread(task, "A");
        MyThread myThread1 = new MyThread(task, "B");
        myThread.start();
        myThread1.start();
        try {
            Thread.sleep(10000);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        long beginTime = Utils.begainTime1;
        if (Utils.begainTime2<Utils.begainTime1){
            beginTime = Utils.begainTime2;
        }
        long endTime = Utils.endTime1;
        if (Utils.endTime2>Utils.endTime1){
            endTime = Utils.endTime2;
        }
        System.out.println("耗时:" + (endTime-beginTime)/1000 + "s");


    }


}

输出内容:

begin task
长时间处理任务后从远程返回的值1 threadName=A
长时间处理任务后从远程返回的值2 threadName=A
end task
begin task
长时间处理任务后从远程返回的值1 threadName=B
长时间处理任务后从远程返回的值2 threadName=B
end task
耗时:6s

从运行时间上来看,synchronized方法的问题很明显。可以使用synchronized同步块来解决这个问题。但是要注意synchronized同步块的使用方式,如果synchronized同步块使用不好的话并不会带来效率的提升。

将上文的Task.class文件修改如下:

public void longTimeTask(){
        try {
            System.out.println("begin task");
            Thread.sleep(3000);
            String data1 = "长时间处理任务后从远程返回的值1 threadName=" + Thread.currentThread().getName();
            String data2 = "长时间处理任务后从远程返回的值2 threadName=" + Thread.currentThread().getName();
            synchronized (this){
                getData1 = data1;
                getData2 = data2;
            }
            System.out.println(getData1);
            System.out.println(getData2);
            System.out.println("end task");
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }

输出如下:

begin task
begin task
长时间处理任务后从远程返回的值1 threadName=B
长时间处理任务后从远程返回的值2 threadName=A
end task
长时间处理任务后从远程返回的值1 threadName=A
长时间处理任务后从远程返回的值2 threadName=A
end task
耗时:3s

从上面代码可以看出当一个线程访问一个对象的synchronized同步代码块时,另一个线程任然可以访问该对象非synchronized同步代码块。不在synchronized块中的就是异步执行,在synchronized块中就是同步执行。

synchronized代码块之间的同步性

当一个线程访问一个对象的synchronized(this)同步代码块时,其他线程对同一个object中的其他synchronized(this)同步代码块访问将被阻塞。

如果在一个类中有很多个synchronized方法,这是虽然能实现同步,但会受到阻塞。如果使用同步代码块锁非this对象,则synchronized(非this)代码块中的程序与同步方法是异步的,不与其他this同步方法争抢this锁。

静态同步synchronized方法与synchronized(class)代码块

关键字synchronized还可以在static方法是使用,是对当前的*.java文件的Class类进行加锁。非静态的synchronized关键字是给对象加锁。

public static void printA() {
        synchronized (Service.class) {
            try {
                System.out.println(
                        "线程名称为:" + Thread.currentThread().getName() + "在" + System.currentTimeMillis() + "进入printA");
                Thread.sleep(3000);
                System.out.println(
                        "线程名称为:" + Thread.currentThread().getName() + "在" + System.currentTimeMillis() + "离开printA");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    synchronized public static void printB() {
        System.out.println("线程名称为:" + Thread.currentThread().getName() + "在" + System.currentTimeMillis() + "进入printB");
        System.out.println("线程名称为:" + Thread.currentThread().getName() + "在" + System.currentTimeMillis() + "离开printB");
    }

    synchronized public void printC() {
        System.out.println("线程名称为:" + Thread.currentThread().getName() + "在" + System.currentTimeMillis() + "进入printC");
        System.out.println("线程名称为:" + Thread.currentThread().getName() + "在" + System.currentTimeMillis() + "离开printC");
    }
public class Main {

    public static void main(String[] args){
        Service service = new Service();
        new Thread(Service::printA, "A").start();
        new Thread(Service::printB, "B").start();
        new Thread(() -> service.printC(), "C").start();


    }
}

输出内容:

线程名称为:A在1552262297299进入printA
线程名称为:C在1552262297300进入printC
线程名称为:C在1552262297300离开printC
线程名称为:A在1552262300301离开printA
线程名称为:B在1552262300301进入printB
线程名称为:B在1552262300301离开printB

从运行结果可以看出:静态同步synchronized方法与synchronized(class)代码块持有的锁一样,都是Class锁,Class锁对对象的所有实例起作用。synchronized关键字加到非static静态方法上持有的是对象锁。线程A,B和线程C持有的锁不一样,所以A和B运行同步,但是和C运行不同步。

数据类型String的常量池特性

JVM具有String常量池缓存的功能,将synchronized(string)与String联合使用时会出现一些问题。

 String s1 = "a";
    String s2="a";
    System.out.println(s1==s2);//true

比如两个同步方法都是synchronized("abc"){}那么多线程会持有相同的锁,所以大多数同步代码块不用String作为锁。

本文代码:GitHub


欢迎关注公众号:

公众号微信