验证了Synchronized的代价,一使用会将所有带有Synchronized的方法都锁建议使用Lock,及Synchronized块
代码块
package com.example.thread;
public class SynchroizedUserBean {
private Integer i = 0 ;
public synchronized Integer getI() {
return i;
}
public synchronized void setI(Integer i) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.i = i;
System.out.println("设置完成 值 :" + i);
}
public Integer getValue(){
synchronized(i){
return i;
}
}
public Integer getVal(){
return i;
}
}
package com.example.thread;
/**
* 验证synchronized是不是会锁住整个对象
* @author Administrator
*
*/
public class SynUserThreadTest {
/**
*
* 事实证明:
* 一个BEAN内使用了同样的synchronized关键字的所有方法,都会被锁住,访问任何一个带synchronized关键字的方法都会被锁住,不允许访问,直到释放锁
* 未带synchronized关键字方法访问不受锁影响
* 方法内带了synchronized块的也不受影响
* @param args
*/
public static void main(String[] args) {
SynchroizedUserBean user = new SynchroizedUserBean();
try {
new Thread(new Runnable() {
@Override
public void run() {
user.setI(3);
}
}).start();
Thread.sleep(500);
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("获取用户值 getI:" + user.getI());
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("获取用户值getVal :" + user.getVal());
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("获取用户值getValue :" + user.getValue());
}
}).start();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}