多线程脏读示例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dongyuxu342719/article/details/88864292
import java.util.concurrent.TimeUnit;

/**
 * 脏读
 * @author SN
 *
 */
public class DirtyRead {
	private String username="aa";
	private String hobby="music";
	
	//下面是同步方法,可以保证更新的原子性
	public synchronized void setValue() throws InterruptedException{
		username="bb";
		TimeUnit.SECONDS.sleep(4);
		hobby="marathon";
		System.out.println("实际数据,username:"+username+",hobby:"+hobby);
	}
	
	//下面的读操作,没有保证同步
	public /*synchronized*/ void getValue(){
		System.out.println("获取到的数据,username:"+username+",hobby:"+hobby);
	}
	
	/*对于一些写操作耗时较长的操作,如果没有保证读同步操作,可能会导致脏读的发生,
	所以在实际业务中需要考虑仔细,不能只在写操作进行同步,读操作同样需要进行同步*/
	public static void main(String[] args) {
		final DirtyRead dr=new DirtyRead();
		Thread t1=new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					dr.setValue();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
		t1.start();
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		dr.getValue();
	}
}

猜你喜欢

转载自blog.csdn.net/dongyuxu342719/article/details/88864292