java并发访问_java并发访问--sychronized

publicVar类:

package com.threades;

public class publicVar {

public String username;

public String password;

synchronized public void setValue(String username,String password){

try {

this.username=username;

Thread.sleep(2000);

this.password=password;

System.out.println("setValue method thread name :"+Thread.currentThread().getName()+"username= "+username+"password= "+password);

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

}

}

public void getValue(){

System.out.println("setValue method thread name :"+Thread.currentThread().getName()+"username= "+username+"password= "+password);

}

}

threadA类:

package com.threades;

public class threadA extends Thread{

private publicVar var;

public threadA(publicVar var){

super();

this.var=var;

}

public void run(){

super.run();

var.setValue("B", "BB");

}

}

run类:

package com.threades;

public class Run {

public static void main(String[] args) {

try {

publicVar var=new publicVar();

threadA A=new threadA(var);

A.setName("A");

A.start();

A.sleep(200);

var.getValue();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

运行结果为:

setValue method thread name :main username= Bpassword= null

setValue method thread name :A username= Bpassword= BB

若在publicVar中的getValue()方法前加synchronized关键字

synchronized public void getValue(){

System.out.println("setValue method

thread name :"+Thread.currentThread().getName()+"username=

"+username+"password= "+password);

}

运行结果则变成:

setValue method thread name :A username= Bpassword= BB

setValue method thread name :main username= Bpassword= BB

结论:当A调用对象的加入synchronized的方法时,A就获得了该方法的锁,其他线程则等A执行完毕再调用,但是B可以随时调用对象的其他非synchronized方法。

当B执行完非synchronized方法,若A未执行完成,则B需要等待A执行完synchronized方法之后B才执行synchronized方法,此时A已完成username以及password,就不存在读脏数据了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值