JAVA的死锁以及同步方法

同步方法及同步块

synchronized方法和synchronized块

public synchronized void method(int args){};

synchronized方法控制对“对象”的访问,每一个对象对应一把锁,需要用synchronized方法调用该方法的对象的锁才能执行;一旦执行,就会独占;

锁的对象得是变化的量;

package ThreadThree;
​
public class TicketUnsafe {
    public static void main(String[] args) {
        tickettt t=new tickettt();
        new Thread(t,"小明").start();
        new Thread(t,"小红").start();
        new Thread(t,"黄牛").start();
    }
}
class tickettt implements Runnable {
    private int ticket=20;
    boolean stoping=true;
    @Override
    public void run() {
        while (stoping){
            buy();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public synchronized void buy(){
        if(ticket<=0){
            stoping=false;
            return;
        }
        System.out.println(Thread.currentThread().getName()+ticket--);
    }
}

死锁

多个线程各自占有一些共享的资源,而相互等待其他线程占有的资源才能运行,相互等待而停止执行;

public class DeadLock {
    public static void main(String[] args) {
        swap s1=new swap(1,"小张");
        swap s2=new swap(2,"小李");
        s1.start();
        s2.start();
    }
}
 class money{
​
 }
 class thing{
​
 }
 class swap extends Thread {
     static money m1 = new money();
     static thing t1 = new thing();
     String name;
     int buy;
​
     swap(int buy, String name) {
         this.buy = buy;
         this.name = name;
     }
​
     public void run() {
         try {
             swap();
         } catch (InterruptedException e) {
             e.printStackTrace();
         }
​
     }
​
     public void swap() throws InterruptedException {
         if (buy == 1) {
             synchronized (m1) {
                 System.out.println(this.name + "获得钱的锁");
                 Thread.sleep(100);
             }
             synchronized (t1) {
                 System.out.println(this.name + "获得东西的锁");
​
             }
         } else {
             synchronized (t1) {
                 System.out.println(this.name + "获得东西的锁");
                 Thread.sleep(300);
             }
             synchronized (m1) {
                 System.out.println(this.name + "获得钱的锁");
             }
         }
​
​
     }
 }

1、一个资源只能被一个进程使用;

2、一个进程请求资源堵塞的时候,会对已获得的资源保持不放;

3、不剥夺,在进程使用完之前不能强行剥夺;

4、若干个进程形成一种首尾相接等待资源的情况;


Lock锁

ReentranLock类可重复锁;拥有和synchronized相同的并发性;

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值