线程同步之脏读问题

阅读更多
  • 线程同步,要确保业务完整性(原子性),多个方法都要使用synchronized,否则会出现脏读问题

  demo:

 

  

package com.zan;
/**
 *  保持业务整体完整,都要使用synchronized,来确保原子性
 */
public class DirtyRead {

	private String username = "lisi";
	private String password = "123456";
	
	public synchronized void setValue(String username, String password){
		this.username = username;
		try {
			
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		this.password = password;
		
		System.out.println("setValue的值username = " + username + " , password = " + password);
	}
	
	//加synchronized ,确保在设值过程中,不会出现脏读。即要设值后才能去读
	public synchronized 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("wangwu", "new123456");		
			}
		});
		t1.start();
		
		Thread.sleep(1000);
		
		dr.getValue();
	}
	
	
	
}

 

你可能感兴趣的:(线程,java)