多线程Synchronized验证

验证了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();
    }

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值