【Java 线程安全】

78 篇文章 0 订阅

多线程导致数据问题

package com.yuzhenc.thread;

/**
 * @author: yuzhenc
 * @date: 2022-04-05 15:02:01
 * @desc: com.yuzhenc.thread
 * @version: 1.0
 */
public class Test02 {
    public static void main(String[] args) {
        TestThread1 t = new TestThread1();
        Thread thread1 = new Thread(t,"窗口1");
        thread1.start();
        Thread thread2 = new Thread(t,"窗口2");
        thread2.start();
        Thread thread3 = new Thread(t,"窗口3");
        thread3.start();
    }
}

class TestThread1 implements Runnable {
    //总共10张票
    int ticketNum = 10;
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (ticketNum > 0) {
                System.out.println("我在"+Thread.currentThread().getName()+"买到了第"+ticketNum--+"张票");
            }
        }
    }
}

在这里插入图片描述

同步代码块

package com.yuzhenc.thread;

/**
 * @author: yuzhenc
 * @date: 2022-04-05 21:15:36
 * @desc: com.yuzhenc.thread
 * @version: 1.0
 */
public class Test09 {
    public static void main(String[] args) {
        TestThread8 t = new TestThread8();
        Thread thread1 = new Thread(t,"窗口1");
        thread1.start();
        Thread thread2 = new Thread(t,"窗口2");
        thread2.start();
        Thread thread3 = new Thread(t,"窗口3");
        thread3.start();

        TestThread9 t1 = new TestThread9();
        Thread thread4 = new Thread(t1,"窗口4");
        thread4.start();
        Thread thread5 = new Thread(t,"窗口5");
        thread5.start();
        Thread thread6 = new Thread(t,"窗口6");
        thread6.start();
    }
}
class TestThread8 implements Runnable {
    //总共10张票
    int ticketNum = 10;
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            synchronized (this) {//把具有安全隐患的代码锁住,this就是这个锁,锁多了会影响效率
                if (ticketNum > 0) {
                    System.out.println("我在"+Thread.currentThread().getName()+"买到了第"+ticketNum--+"张票");
                }
            }
        }
    }
}

class TestThread9 implements Runnable {
    //总共10张票
    int ticketNum = 10;
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            synchronized (TestThread9.class) {//锁必须多个线程用的是同一把锁
                if (ticketNum > 0) {
                    System.out.println("我在"+Thread.currentThread().getName()+"买到了第"+ticketNum--+"张票");
                }
            }
        }
    }
}

同步方法

package com.yuzhenc.thread;

/**
 * @author: yuzhenc
 * @date: 2022-04-05 21:25:21
 * @desc: com.yuzhenc.thread
 * @version: 1.0
 */
public class Test10 {
    public static void main(String[] args) {
        TestThread10 t = new TestThread10();
        Thread thread1 = new Thread(t,"窗口1");
        thread1.start();
        Thread thread2 = new Thread(t,"窗口2");
        thread2.start();
        Thread thread3 = new Thread(t,"窗口3");
        thread3.start();
    }
}

class TestThread10 implements Runnable {
    //总共10张票
    static int ticketNum = 10;
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            buyTicket();
        }
    }
    //同步方法
    public static synchronized void buyTicket(){
        if (ticketNum > 0) {
            System.out.println("我在"+Thread.currentThread().getName()+"买到了第"+ticketNum--+"张票");
        }
    }
}
  • 不要将run()定义为同步方法
  • 非静态同步方法的同步监视器是this
  • 静态同步方法的同步监视器是 类名.class 字节码信息对象
  • 同步代码块的效率要高于同步方法,原因:同步方法是将线程挡在了方法的外部,而同步代码块锁将线程挡在了代码块的外部,但是却是方法的内部
  • 同步方法的锁是this,一旦锁住一个方法,就锁住了所有的同步方法;同步代码块只是锁住使用该同步监视器的代码块,而没有锁住使用其他监视器的代码块

Lock锁

  • synchronized是Java中的关键字,这个关键字的识别是靠JVM来识别完成的呀。是虚拟机级别的
  • Lock锁是API级别的,提供了相应的接口和对应的实现类,这个方式更灵活,表现出来的性能优于之前的方式
package com.yuzhenc.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: yuzhenc
 * @date: 2022-04-05 21:37:23
 * @desc: com.yuzhenc.thread
 * @version: 1.0
 */
public class Test11 {
    public static void main(String[] args) {
        TestThread11 t = new TestThread11();
        Thread thread1 = new Thread(t,"窗口1");
        thread1.start();
        Thread thread2 = new Thread(t,"窗口2");
        thread2.start();
        Thread thread3 = new Thread(t,"窗口3");
        thread3.start();
    }
}
class TestThread11 implements Runnable {
    //总共10张票
    int ticketNum = 10;
    Lock lock = new ReentrantLock();//接口 = 实现类
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            lock.lock();//打开锁
            try {
                if (ticketNum > 0) {
                    System.out.println("我在"+Thread.currentThread().getName()+"买到了第"+ticketNum--+"张票");
                }
            } catch (Exception e) {
                System.out.println(e.getStackTrace());
            } finally {
                lock.unlock();//关闭锁
            }
        }
    }
}
  • Lock是显式锁(手动开启和关闭锁,别忘记关闭锁),synchronized是隐式锁
  • Lock只有代码块锁,synchronized有代码块锁和方法锁
  • 使用Lock锁,JVM将花费较少的时间来调度线程,性能更好,并且具有更好的扩展性(提供更多的子类)
  • 优先使用顺序:Lock----同步代码块(已经进入了方法体,分配了相应资源)----同步方法(在方法体之外)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

sqlboy-yuzhenc

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

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

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

打赏作者

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

抵扣说明:

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

余额充值