JAVA多线程基础

1.线程的周期

周期流程图

2.线程的实现方法

/**
 * @Author: zzj
 * @Date: 2020/4/21 12:21
 */
public class ThreadCreat {
    public static void main(String[] args) {
        MyThread thread1 = new MyThread();
        //通过set方法设置线程名
        thread1.setName("Thread子线程");
        //设置优先级1~10
        thread1.setPriority(10);
        thread1.start();
        //方式2:实现Runnable接口
        Runnable thread2 = () -> {
            System.out.println("线程名:"+Thread.currentThread().getName());
        };
        //使用有参构造方法设置线程名
        Thread r = new Thread(thread2,"Runnable子线程");
        r.start();
    }
}
class MyThread extends Thread{
    //方式1:继承Thread类并重写run方法;
    @Override
    public void run() {
        System.out.println("线程名:"+Thread.currentThread().getName());
    }
}

3.线程的临界问题

假设有四个售票员在同时售卖100张门票,我们开启四个线程来并发操作

/**
 * @Author: zzj
 * @Date: 2020/4/21 12:48
 */
public class Ticket {
    public static void main(String[] args) {
        //实例化四个售票员开始售票
        Runnable r = () -> {
            while(TicketSel.ticketNum > 0){
                System.out.println(Thread.currentThread().getName() + "卖出一张票,剩余" + --TicketSel.ticketNum + "张");
            }
        };
        Thread r1 = new Thread(r,"Thread1");
        Thread r2 = new Thread(r,"Thread2");
        Thread r3 = new Thread(r,"Thread3");
        Thread r4 = new Thread(r,"Thread4");
        r1.start();
        r2.start();
        r3.start();
        r4.start();
    }
}
class TicketSel{
    //设置代售门票总数
    public static int ticketNum = 500;
}

运行结果我们发现不仅仅每次余票的数量是乱的,而且当余票为0时依旧在卖

4.解决方法

使用隐式锁synchronized关键字

 Runnable r = () -> {
     while(TicketSel.ticketNum > 0){
         synchronized (""){
             //进行二次校验,防止出现超卖
             if(TicketSel.ticketNum <= 0){
                 return;
             }
             System.out.println(Thread.currentThread().getName() + "卖出一张票,剩余" + --TicketSel.ticketNum + "张");
         }
     }
 };

使用显式锁ReentrantLock类

 ReentrantLock lock = new ReentrantLock();
 //实例化四个售票员开始售票
 Runnable r = () -> {
     while(TicketSel.ticketNum > 0){
         lock.lock();
         //进行二次校验,防止出现超卖
         if(TicketSel.ticketNum <= 0){
             return;
         }
         System.out.println(Thread.currentThread().getName() + "卖出一张票,剩余" + --TicketSel.ticketNum + "张");
         lock.unlock();
     }
 };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值