脏读
脏读:读到在写的过程中还没有写完的数据
原因:写!加锁了,读没有加锁。(业务代码没有对读加锁,且线程共享进程内部数据!)
设计程序时候,一定要注意业务的整体性。也就是要注意上节学的资源的共享,则一定要同步。不然就会发生错误。比如经典的脏读(dirtyread)
/**
* 对业务不加锁容易产生脏读问题/DirtyRead/
* @author Forever
*
*/
import java.util.concurrent.TimeUnit;
public class Java_dxc008 {
String name;
double balance;
public synchronized void set(String name, double balance) {
this.name = name;
try {
Thread.sleep(3000);
}catch(InterruptedException e) {
e.printStackTrace();
}
this.balance = balance;
}
public /*synchronized*/ double getBalace(String name) {
return this.balance;
}
public static void main(String[] args) {
Java_dxc008 a= new Java_dxc008();
new Thread(()->a.set("zhangsan", 100.0)).start();
try {
TimeUnit.SECONDS.sleep(2);
}catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println(a.getBalace("zhangsan"));
try {
TimeUnit.SECONDS.sleep(2);
}catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println(a.getBalace("zhangsan"));
}
}
输出:
0.0
100.0
还是那句话:对于对象的同步和异步的方法,我们在设计自己的程序的时候,一定要考虑问题的整体,不然就会出现数据不一致的错误。