线程脏读

 脏读

  对于对象的同步和异步方法,我们在设计自己的程序的时候,一定要考虑问题的整体性,不然会出现数据不一致的错误,很经典的错误就是脏读(dirtyRead)

public class DirtyRead {

	private String username = "bjsxt";
	private String password = "123";
	
	public synchronized void setValue(String username, String password){
		this.username = username;
		
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		this.password = password;
		
		System.out.println("setValue最终结果:username = " + username + " , password = " + password);
	}
	
	public void getValue(){
		System.out.println("getValue方法得到:username = " + this.username + " , password = " + this.password);
	}
	
	
	public static void main(String[] args) throws Exception{
		
		final DirtyRead dr = new DirtyRead();
		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				dr.setValue("z3", "456");		
			}
		});
		t1.start();
		Thread.sleep(1000);
		
		dr.getValue();
	}
结果:
getValue方法得到:username = z3 , password = 123
setValue最终结果:username = z3 , password = 456

 结果分析: 预计需要的结果是username = z3 , password = 456 但是没有,为了保持业务的原子性,setValue时不需要getValue,需要在getValue方法上加上synchronized关键字,不然会出现业务错误

猜你喜欢

转载自wen303614.iteye.com/blog/2408204