004JAVA多线程脏读

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了004JAVA多线程脏读相关的知识,希望对你有一定的参考价值。

package com.skcc.mthread;

public class A_003DirtRead {

private String username="zjy";
private String password="123456";

public A_003DirtRead() {
    // TODO Auto-generated constructor stub
}

public synchronized void setValue(String username,String password) {
    this.username = username;
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    this.password = password;
    System.out.println("Set Result username="+this.username + " password="+this.password);
}

/****
 * synchronized
 * ****/
public  void getValue() {
    System.out.println("Get Value username="+username + " password="+password);
}

public static void main(String[] args) {
    // TODO Auto-generated method stub

    A_003DirtRead dirtRead = new A_003DirtRead();
    //dirtRead.getValue();
    new Thread(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            dirtRead.setValue("tomcat", "jboss");
        }
    }).start();

    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    dirtRead.getValue();

}

}

以上是关于004JAVA多线程脏读的主要内容,如果未能解决你的问题,请参考以下文章

java多线程,如何防止脏读数据

java 多线程8 : synchronized锁机制 之 方法锁

Java多线程4:synchronized锁机制

Java多线程之对写业务加锁,对读业务不加锁,会产生脏读

java多线程

java多线程基本概述——同步