JAVA多线程基础

1.线程的周期

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();
     }
 };

你可能感兴趣的:(JAVA笔记)