java read也需要加锁
  nzOJE50ROQlt 2023年11月02日 68 0


今天被问到read需不需要加锁,结果没答上来。自己写了一个程序试了一下,答案是肯定的,read加锁是为了保证执行的顺序,让线程不会读到脏数据。

public class TestThread {
	private int a = 1;

	public synchronized void add(){
		this.a = this.a + 1;
		System.out.println(Thread.currentThread().getName() + "current a is " + a);
	}

	public int get(){
		System.out.println("current a is " + a);
		return a;
	}

	public static void main(String[] args) throws Exception{
		final TestThread testThread = new TestThread();
		Thread t1 = new Thread(new Runnable(){
			public void run(){
				testThread.add();
				//make sure the second thread to be executed at this moment
				try {
					Thread.sleep(10000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				testThread.get();
			}
		}
		);

		Thread t2 = new Thread(new Runnable(){
			public void run(){
				//make sure the first thread to be started firstly at beginning
				try {
					Thread.sleep(5000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				testThread.add();
				testThread.get();
			}
		}
		);

		t1.start();
		t2.start();
	}
}




output:


Thread-0current a is 2


Thread-1current a is 3


current a is 3


current a is 3



如果对testThread.add();testThread.get();加锁就不会出现刚才读到脏数据的问题。


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

上一篇: Restful vs RPC 下一篇: velocity 缓存设置
  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  xaeiTka4h8LY   2024年05月17日   48   0   0 数据库JavaSQL
  2iBE5Ikkruz5   2023年12月12日   91   0   0 JavaJavaredisredis
nzOJE50ROQlt