2.2.7锁定非this对象synchronized(this)

来源:互联网 发布:软件测试通过的标准 编辑:程序博客网 时间:2024/06/08 18:53

package cha02.execise17;/** * Created by sunyifeng on 17/9/25. */public class Service {    private String usernameParam;    private String passwordParam;    private String anyString = new String();    public void setPasswordParam(String usernameParam, String passwordParam){        try{            synchronized (anyString){                System.out.println("进入线程名称为:" + Thread.currentThread().getName());                this.usernameParam = usernameParam;                Thread.sleep(3000);                this.passwordParam = passwordParam;                System.out.println("离开线程名称为:" + Thread.currentThread().getName());            }        }catch (InterruptedException e){            e.printStackTrace();        }    }}
package cha02.execise17;/** * Created by sunyifeng on 17/9/25. */public class ThreadA extends Thread {    private Service service;    public ThreadA(Service service) {        super();        this.service = service;    }    @Override    public void run() {        service.setPasswordParam("a", "aa");    }}
package cha02.execise17;/** * Created by sunyifeng on 17/9/25. */public class ThreadB extends Thread {    private Service service;    public ThreadB(Service service) {        super();        this.service = service;    }    @Override    public void run() {        service.setPasswordParam("b", "bb");    }}
package cha02.execise17;/** * Created by sunyifeng on 17/9/25. */public class Run {    public static void main(String[] args) {        Service service = new Service();        // 线程A        ThreadA threadA = new ThreadA(service);        threadA.setName("A");        threadA.start();        // 线程B        ThreadB threadB = new ThreadB(service);        threadB.setName("B");        threadB.start();    }}
运行结果:

进入线程名称为:A
离开线程名称为:A
进入线程名称为:B
离开线程名称为:B

程序分析:

如果类中有多个同步方法,这时虽然能实现同步,但会受到影响,如果使用非this对象,则可以实现异步,提高运行效率。

更改以上代码如下:

package cha02.execise17;/** * Created by sunyifeng on 17/9/25. */public class Service {    private String usernameParam;    private String passwordParam;    public void setPasswordParam(String usernameParam, String passwordParam){        try{            String anyString = new String(); // FIXME: 注意这里            synchronized (anyString){                System.out.println("进入线程名称为:" + Thread.currentThread().getName());                this.usernameParam = usernameParam;                Thread.sleep(3000);                this.passwordParam = passwordParam;                System.out.println("离开线程名称为:" + Thread.currentThread().getName());            }        }catch (InterruptedException e){            e.printStackTrace();        }    }}
运行结果如下:

进入线程名称为:A
进入线程名称为:B
离开线程名称为:A
离开线程名称为:B

程序分析:

使用synchronized(非this)锁,对象监视器必须是同一个对象。以上anyString放在方法内部创建,线程每次进来都是不同对象。

阅读全文
0 0
原创粉丝点击