对象及变量的并发访问-----synchronized同步----- 脏读
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了对象及变量的并发访问-----synchronized同步----- 脏读相关的知识,希望对你有一定的参考价值。
一、接上一步,如果变量在方法外部,对变量加上关键字synchonzied即可
变量加synchronized
package service; /** * Created by zhc on 2017/10/10 */ public class HasSelfPrivateNum { private int num = 0; synchronized public void addI(String username) { try { if (username.equals("a")) { num = 100; System.out.println("a is set over"); } else { num = 200; System.out.println("b is set over"); } System.out.println(username + " num = " + num); } catch (Exception e) { e.printStackTrace(); } } }
二、出现脏读情况
首先给出一个实体类,通俗讲,set方法进行加锁,get没有
package entity; /** * Created by zhc on 2017/10/10 */ public class PublicVar { public String username = "A"; public String password = "AA"; synchronized public void setValue(String username,String password){ try { this.username = username; Thread.sleep(5000); this.password = password; System.out.println(" setValue method thread name "+Thread.currentThread().getName() +"username and password ="+username+" "+password); }catch (InterruptedException e){ e.printStackTrace(); } } public void getValue(){ System.out.println(" getValue method thread name "+Thread.currentThread().getName() +"username and password ="+username+" "+password); } }
然后线程进行设值,然后读取。
package extthread; import entity.PublicVar; /** * Created by zhc on 2017/10/10 */ public class ThreadC extends Thread { private PublicVar publicVar; public ThreadC(PublicVar publicVar){ super(); this.publicVar = publicVar; } @Override public void run() { super.run(); publicVar.setValue("B","BB"); } }
开启线程,进行测验
Run
出现结果:
getValue method thread name main username and password =B AA
setValue method thread name Thread-0 username and password =B BB
出现脏读情况,发现synchronized某方法(set),可以获得此方法锁,也就是获得该对象锁,但是get方法因为未被synchronized,则被调用时无关是否被锁。
但是如果get方法也被synchronized,那么B线程的get方法调用一定要等A线程执行完set先结束才行。
我们对get方法加synchronized,
package entity; /** * Created by zhc on 2017/10/10 */ public class PublicVar { public String username = "A"; public String password = "AA"; synchronized public void setValue(String username,String password){ try { this.username = username; Thread.sleep(5000); this.password = password; System.out.println(" setValue method thread name "+Thread.currentThread().getName() +" username and password ="+username+" "+password); }catch (InterruptedException e){ e.printStackTrace(); } } synchronized public void getValue(){ System.out.println(" getValue method thread name "+Thread.currentThread().getName() +" username and password ="+username+" "+password); } }
看看结果:
setValue method thread name Thread-0 username and password =B BB
getValue method thread name main username and password =B BB
以上是关于对象及变量的并发访问-----synchronized同步----- 脏读的主要内容,如果未能解决你的问题,请参考以下文章