synchronized块和synchronized函数

synchronized块和synchronized函数锁住的都是当前对象。

class threadOne implements Runnable{
    public static int num=0;
    public static Object ob=new Object();
    public boolean b=true;
    @Override
    public void run(){
        if(b==true){
            synchronized (this){
                try{
                    Thread.sleep(600);
                }catch (Exception e){
                    e.printStackTrace();
                }
                while(num!=10){
                    num+=1;
                    System.out.println("run-num:"+num);
                }
            }
        }else{
            compute();
        }
    }

    public synchronized void compute(){
        while(num!=10){
            num+=1;
            System.out.println("compute-num:"+num);
        }
    }

}

public class threadTest {
    public static void main(String ...args){
        threadOne one=new threadOne();
        Thread t1=new Thread(one);
        Thread t2=new Thread(one);
        t1.start();
        try{
            Thread.sleep(300);
        }catch (Exception e){
            e.printStackTrace();
        }
        one.b=false;
        t2.start();
    }
}
D:\Java\jdk1.8.0_151\bin\java.exe "-javaagent:D:\idea\IntelliJ IDEA Community Edition 2018.2.5\lib\idea_rt.jar=1426:D:\idea\IntelliJ IDEA Community Edition 2018.2.5\bin" -Dfile.encoding=UTF-8 -classpath D:\Java\jdk1.8.0_151\jre\lib\charsets.jar;D:\Java\jdk1.8.0_151\jre\lib\deploy.jar;D:\Java\jdk1.8.0_151\jre\lib\ext\access-bridge-64.jar;D:\Java\jdk1.8.0_151\jre\lib\ext\cldrdata.jar;D:\Java\jdk1.8.0_151\jre\lib\ext\dnsns.jar;D:\Java\jdk1.8.0_151\jre\lib\ext\jaccess.jar;D:\Java\jdk1.8.0_151\jre\lib\ext\jfxrt.jar;D:\Java\jdk1.8.0_151\jre\lib\ext\localedata.jar;D:\Java\jdk1.8.0_151\jre\lib\ext\nashorn.jar;D:\Java\jdk1.8.0_151\jre\lib\ext\sunec.jar;D:\Java\jdk1.8.0_151\jre\lib\ext\sunjce_provider.jar;D:\Java\jdk1.8.0_151\jre\lib\ext\sunmscapi.jar;D:\Java\jdk1.8.0_151\jre\lib\ext\sunpkcs11.jar;D:\Java\jdk1.8.0_151\jre\lib\ext\zipfs.jar;D:\Java\jdk1.8.0_151\jre\lib\javaws.jar;D:\Java\jdk1.8.0_151\jre\lib\jce.jar;D:\Java\jdk1.8.0_151\jre\lib\jfr.jar;D:\Java\jdk1.8.0_151\jre\lib\jfxswt.jar;D:\Java\jdk1.8.0_151\jre\lib\jsse.jar;D:\Java\jdk1.8.0_151\jre\lib\management-agent.jar;D:\Java\jdk1.8.0_151\jre\lib\plugin.jar;D:\Java\jdk1.8.0_151\jre\lib\resources.jar;D:\Java\jdk1.8.0_151\jre\lib\rt.jar;E:\threadTest\out\production\threadTest threadTest
run-num:1
run-num:2
run-num:3
run-num:4
run-num:5
run-num:6
run-num:7
run-num:8
run-num:9
run-num:10

Process finished with exit code 0

 

以上是运行结果,证明了后面compute函数无法竞争到锁。

有问题可以在留言区交流。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值