public class Test1{
public static void main(String[] args) throws InterruptedException {
Demo1 demo1= new Demo1();
new Thread(new Runnable() {
@Override
public void run() {
try {
demo1.set(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
Thread.sleep(1);//主线程休息1ms,保证子线程先访问
demo1.get();
}
}
class Demo1{
int a=100;
Synchroized public void set(int a) throws InterruptedException {
System.out.println("准备赋值");
Thread.sleep(10);//保证主线程先输出a
this.a=a;
System.out.println(Thread.currentThread().getName()+"说a is"+a);
}
public void get(){
System.out.println(Thread.currentThread().getName()+"说a is"+a);
}
}
/**
准备赋值
main说a is100
Thread-0说a is10
Process finished with exit code 0**/
虽然子线程先调用set获得锁,但没有完成赋值,被main线程错误输出,这就是脏读,那该如何保证不出错呢
synchronized public void get()
只需在另个方法加上对象锁synchronized,不同线程调用同一实例的不同的同步方法会同步等待
所以main要调用get,必须等到set执行完,才可以输出,避免脏读