JUC并发编程

84 阅读1分钟

JUC并发编程

学习代码位置: gitee.com/zhuhuijie/j…

1 回顾 java 多线程知识

代码见demo1

1.1 线程创建的三种方式

public class Test1 extends Thread {

    // 线程的几种状态 :
    // 新生 NEW -》
    // 运行 RUNNABLE -》
    // 阻塞 BLOCKED -》
    // 等待 WAITING -》
    // 超时等待 TIME_WAITING -》
    // 终止 TERMINATED
    public static void main(String[] args) {

        System.out.println("计算机核心:" + Runtime.getRuntime().availableProcessors());

        new Test1().start();

        new Thread(new Test01()).start();

        Test001 callable = new Test001();
        FutureTask<Integer> task = new FutureTask<>(callable);
        new Thread(task).start();

    }

    @Override
    public void run() {
        System.out.println("我是线程的第一种种创建方式!-----继承Thread类");
        super.run();
    }
}

class Test01 implements Runnable {

    @Override
    public void run() {
        System.out.println("我是线程的第二种创建方式!-----实现Runnable接口");
    }
}

class Test001 implements Callable<Integer> {

    // 可以有返回值 可以抛出异常
    @Override
    public Integer call() throws Exception {

        System.out.println("我是线程的第三种创建方式!----实现Callable接口");

        return null;
    }
}

1.2 lock 锁 与 synchronized 锁

public class Test2SaleTicket {

    public static void main(String[] args) {

        Ticket ticket = new Ticket();

        new Thread(()->{
            for (int i = 0; i < 60; i++) {
                ticket.sale();
            }
        },"小明").start();

        new Thread(()->{
            for (int i = 0; i < 60; i++) {
                ticket.sale();
            }
        },"小红").start();

        new Thread(()->{
            for (int i = 0; i < 60; i++) {
                ticket.sale();
            }
        },"小华").start();
    }

}

// 资源类 OOP
class Ticket {

    private int number = 50;

   /* ----------------------synchronized 锁--------------------------------------------------------------
   public synchronized void sale() {
        if (number > 0) {
            System.out.println(Thread.currentThread().getName() + "买了一张票,剩余票数:" + (--number));
        }
    }*/

   // lock 锁  与  synchronized 锁
   // synchronized 1.内置关键字-------2.无法判断锁的状态-------3.会自动释放锁
   //              ---4.线程一获得锁阻塞,线程二就会一直等 ---5.可重入锁,不可中断,非公平的------6.锁少量的代码同步问题
   // lock         1.是一个java类-----2.可以判断是否获得锁-----3.需要手动释放
   //              ---4.不会一直等 ---------------------------5.可重入锁,可判断锁,非公平(可以自己设)----6.锁大量的代码
   Lock lock = new ReentrantLock();

    public void sale() {

        lock.lock();  // 加锁

        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "买了一张票,剩余票数:" + (--number));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();  // 解锁
        }
    }

}