4.脏读

对于对象的同步、异步的方法,设计程序的时候一定要考虑问题的整体,出现数据不一致就一个经典的错误。

  1. package demo1;
  2. /**
  3. *
  4. * Created by liudan on 2017/6/3.
  5. */
  6. public class MyThread4 {
  7. private String user = "liudan";
  8. private String pwd = "123456";
  9. private synchronized void setUserValue(String user, String pwd) {
  10. this.user = user;
  11. try {
  12. Thread.sleep(2000);
  13. } catch (InterruptedException e) {
  14. e.printStackTrace();
  15. }
  16. this.pwd = pwd;
  17. System.err.println("setValue 最终结果->:user = " + user + "\t" + "pwd = " + pwd);
  18. }
  19. private void getUserValue() {
  20. System.err.println("getUserValue 设置值:user = " + this.user + "\t" + "pwd = " + this.pwd);
  21. }
  22. /**
  23. * 对一个方法枷加锁,需要考虑功能业务的整体性,同时为set、get加锁,使用 synchronized 关键字,保证业务的原子性,不然则会出现业务的错误。
  24. * @param args
  25. * @throws InterruptedException
  26. */
  27. public static void main(String[] args) throws InterruptedException {
  28. final MyThread4 tUser = new MyThread4();
  29. Thread userThread = new Thread(new Runnable() {
  30. @Override
  31. public void run() {
  32. tUser.setUserValue("testuser","111111");
  33. }
  34. });
  35. userThread.start();
  36. Thread.sleep(1000);
  37. tUser.getUserValue();
  38. }
  39. }
  40. 正确结果输出:private synchronized void getUserValue()
  41. setValue 最终结果->:user = testuser pwd = 111111 getUserValue 设置值:user = testuser pwd = 111111

  42. 错误结果输出:private void getUserValue() 属于异步调用
  43. getUserValue 设置值:user = testuser pwd = 123456 setValue 最终结果->:user = testuser pwd = 111111
posted @ 2017-08-10 02:10  逍遥叹!!  阅读(212)  评论(0编辑  收藏  举报