线程同步机制(线程安全与锁)

并发

并发:同一个对象被多个线程同时操作(抢票)

线程同步

线程同步其实就是一种等待机制,多个需要同时访问此对象的线程进入这个对象等待池形成队列,等待前面的线程使用完毕,下一个线程再使用。
在这里插入图片描述

购票实例

package tesy;
public class buyticket {
    public static void main(String[] args) {
        buyTickets buytickets = new buyTickets();
        new Thread(buytickets,"你").start();
        new Thread(buytickets,"我").start();
        new Thread(buytickets,"黄牛").start();

    }
}
class buyTickets implements Runnable{
private int tickets = 100;
boolean flag = true;
    @Override
    public void run() {
        while (flag){
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

    }
    private synchronized void buy() throws InterruptedException {
        if (tickets<=0){
            flag = false;
            return;
        }
//        Thread.sleep(100);
        System.out.println(Thread.currentThread().getName()+"-->"+tickets--);
    }
}

同步方法及同步块

在这里插入图片描述
弊端:
方法里面需要修改的内容才需要锁,锁太多,浪费资源
在这里插入图片描述

CopyOnWriteArrayList

package tesy;

import java.util.concurrent.CopyOnWriteArrayList;
//测试juc安全类型集合
public class testJuc {
    public static void main(String[] args) throws InterruptedException {
        CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
        for (int i = 0; i < 10000; i++) {
            new Thread(() -> {
                    list.add(Thread.currentThread().getName());
            }).start();
        }
        Thread.sleep(3000);
        System.out.println(list.size());
    }
}

死锁

在这里插入图片描述
死锁:多个线程相互抱着对方需要的资源,然后形成僵持

package tesy;
//死锁:多个线程相互抱着对方需要的资源,然后形成僵持
//模拟化妆
public class testLock {
    public static void main(String[] args) {
        Makeup u1 = new Makeup(0,"我");
        Makeup u2 = new Makeup(1,"你");
        u1.start();
        u2.start();
    }

}
//口红
class Lipstick{
}
//镜子
class  Mirror{

}
class Makeup extends Thread{
    //需要的资源只有一个,用static保证只有一个
    static Lipstick lipstick = new Lipstick();
    static  Mirror mirror = new Mirror();
    //选择
    int choice;
    //使用化妆品的人
    String username;
    Makeup(int choice,String username){
        this.choice = choice;
        this.username = username;
    }
    @Override
    public void run() {
        //模拟化妆
        try {
            makeup();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
    //互相持有对方的锁,就是需要对方的资源
    private void makeup() throws InterruptedException {
        if (choice == 0) {
            //获取口红的锁
            synchronized (lipstick) {
                System.out.println(this.username + "获取口红的锁");
                Thread.sleep(1000);
                synchronized (mirror) { //一秒后获取镜子的锁
                    System.out.println(this.username + "获取镜子的锁");

                }
            }
        } else {
            synchronized (mirror) { //一秒后获取镜子的锁
                System.out.println(this.username + "获取镜子的锁");
                Thread.sleep(3000);
                synchronized (lipstick) {//两秒秒后获取口红的锁
                    System.out.println(this.username + "获取口红的锁");

                }
            }

        }
    }
}

修改

package tesy;
//死锁:多个线程相互抱着对方需要的资源,然后形成僵持
//模拟化妆
public class testLock {
    public static void main(String[] args) {
        Makeup u1 = new Makeup(0,"我");
        Makeup u2 = new Makeup(1,"你");
        u1.start();
        u2.start();
    }

}


//口红
class Lipstick{

}

//镜子
class  Mirror{

}


class Makeup extends Thread{
    //需要的资源只有一个,用static保证只有一个
    static Lipstick lipstick = new Lipstick();
    static  Mirror mirror = new Mirror();
    //选择
    int choice;
    //使用化妆品的人
    String username;
    Makeup(int choice,String username){
        this.choice = choice;
        this.username = username;
    }
    @Override
    public void run() {
        //模拟化妆
        try {
            makeup();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
    //互相持有对方的锁,就是需要对方的资源
    private void makeup() throws InterruptedException {
        if (choice == 0) {
            //获取口红的锁
            synchronized (lipstick) {
                System.out.println(this.username + "获取口红的锁");
                Thread.sleep(1000);
            }

            synchronized (mirror) { //一秒后获取镜子的锁
                System.out.println(this.username + "获取镜子的锁");

            }
        } else {
            synchronized (mirror) { //一秒后获取镜子的锁
                System.out.println(this.username + "获取镜子的锁");
                Thread.sleep(3000);
            }
            synchronized (lipstick) {//两秒秒后获取口红的锁
                System.out.println(this.username + "获取口红的锁");

            }

        }
    }
}

避免死锁

在这里插入图片描述

ReentrantLock可重复锁
在这里插入图片描述

package tesy;
import java.util.concurrent.locks.ReentrantLock;
public class Lock {
    public static void main(String[] args) {
        Lock2 lock = new Lock2();
        new Thread(lock).start();
        new Thread(lock).start();
        new Thread(lock).start();
    }
}
class Lock2 implements Runnable{
    int tickt =10;
    //定义lock锁
    private final ReentrantLock locks = new ReentrantLock();

    @Override
    public void run() {
        while (true){
            try {
                locks.lock();  //加锁

                if (tickt>0){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(tickt--);
                }else {
                    break;
                }
            }finally {
                //解锁
                locks.unlock();
            }
        }

    }
}

在这里插入图片描述

synchron与Lock对比

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

啊~小 l i

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值