同步和死锁

存在同步问题的代码:

public class Demo1 implements Runnable{
    
    private int count = 5;

    /**
     * @param args
     */
    public static void main(String[] args) {
        Demo1 demo =new Demo1();
        Thread h1=new Thread(demo);
        Thread h2=new Thread(demo);
        Thread h3=new Thread(demo);
        h1.start();
        h2.start();
        h3.start();

    }

    @Override
    public void run() {
        for(int i=0;i<10;++i){
            if(count>0){
                try{
                    Thread.sleep(1000);
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
                System.out.println(count--);
            }
        }
    }
}

运行结果:

5
4
3
2
1
0
-1

上述结果,出现-1显然是不对的,这是由于在同一时间两个线程对count进行了操作导致的

引入同步代码块和同步方法来解决上述问题

【同步代码块】:

语法格式:

synchronized(同步对象){

 //需要同步的代码

}

public void run() {
        for(int i=0;i<10;++i){
            synchronized (this) {
                if(count>0){
                    try{
                        Thread.sleep(1000);
                    }catch(InterruptedException e){
                        e.printStackTrace();
                    }
                    System.out.println(count--);
                }
            }
        }
    }

【同步方法】

语法格式为synchronized 方法返回类型方法名(参数列表){

    // 其他代码

}

@Override
    public void run() {
        for(int i=0;i<10;++i){
            count();
        }
    }
    
    private synchronized void count(){
        if(count>0){
            try{
                Thread.sleep(1000);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
            System.out.println(count--);
        }
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值