其他分享
首页 > 其他分享> > 2022-08-04 第五组 赖哲栋 学习笔记

2022-08-04 第五组 赖哲栋 学习笔记

作者:互联网

LockSupport工具类

  1. 线程阻塞的工具类,所有的方法都是静态方法,可以让线程在任意位置阻塞。 阻塞之后也有唤醒的方法。
  2. park:停车。如果我们把Thread看成一辆车的话,park就是让车停下
  3. unpark:就是让车启动然后跑起来

区别:

总结:

public static final Object OBJ = new Object();
 
    public void show() {
        try {
            super.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
 
    public static void main(String[] args) throws InterruptedException {
        Runnable runnable = () -> {
            synchronized (OBJ) {
                System.out.println("线程【" + Thread.currentThread().getName() + "】正在执行...");
                // 阻塞
                LockSupport.park("我被阻塞了...");
                if(Thread.currentThread().isInterrupted()){
                    System.out.println("被中断了...");
                }
                System.out.println("继续执行...");
            }
        };
        Thread t1 = new Thread(runnable,"线程一");
        Thread t2 = new Thread(runnable,"线程二");
 
        t1.start();
        Thread.sleep(1000);
        System.out.println(LockSupport.getBlocker(t1));
        t2.start();
        Thread.sleep(3000);
        // 线程中断
        t1.interrupt();
        // 把t2唤醒
        LockSupport.unpark(t2);
        t1.join();
        t2.join();
    }
}

Lock锁

public void show() {
        Lock lock = new Lock() {
            @Override
            public void lock() {
 
            }
            @Override
            public void lockInterruptibly() throws InterruptedException {
 
            }
            @Override
            public boolean tryLock() {
                return false;
            }
            @Override
            public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
                return false;
            }
            @Override
            public void unlock() {
 
            }
            @Override
            public Condition newCondition() {
                return null;
            }
        };
        // 加锁
        lock.lock();
        try {
            // 正常处理业务逻辑
            System.out.println();
        }catch (Exception e){
            // 当出现异常的解决方案
        }finally { // 释放资源,关闭连接,关闭输入输出流
            // 手动释放锁
            lock.unlock();
        }
    }
    public void info() {
        Lock lock = new Lock() {
            @Override
            public void lock() {
            }
            @Override
            public void lockInterruptibly() throws InterruptedException {
 
            }
            @Override
            public boolean tryLock() {
                return false;
            }
            @Override
            public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
                return false;
            }
 
            @Override
            public void unlock() {
 
            }
            @Override
            public Condition newCondition() {
                return null;
            }
        };
        // 如果拿到了锁
        if(lock.tryLock()){
            try {
                // 正常处理业务逻辑
            }catch (Exception e){
                // 当出现异常的解决方案
            }finally { // 释放资源,关闭连接,关闭输入输出流
                // 手动释放锁
                lock.unlock();
            }
        }else {
            // 如果没有拿到锁,则直接做另外的事情
        }
    }
}

Lock接口的实现类ReentrantLock

synchronized和Lock的区别:

  1. Lock是一个接口,synchronized是一个关键字,是由底层(C)语言实现的。
  2. synchronized发生异常时,会自动释放线程占用的锁不会发生死锁。Lock发生异常,若没有主动释放,极有可能占用资源不放手,需要在finally中手动释放锁。
  3. Lock可以让等待锁的线程响应中断,使用synchronized只会让等待的线程一直等待下去,不能响应中断
  4. Lock可以提高多个线程进行读操作的效率。
class Ticket implements Runnable {
 
    private static final ReentrantLock lock = new ReentrantLock();
 
    private static Integer count = 100;
 
    String name;
 
    public Ticket(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        while(Ticket.count > 0){
            lock.lock();
            try {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                if(count > 0){
                    System.out.println(name + "正在卖票,剩余:" + count + "张!");
                    count--;
                    // count = count - 1;
                }
            }finally {
                lock.unlock();
            }
        } 
    }
}
public class Ch03 {
    public static void main(String[] args) {
        Ticket t1 = new Ticket("窗口一");
        Ticket t2 = new Ticket("窗口二");
        Ticket t3 = new Ticket("窗口三");
 
        new Thread(t1).start();
        new Thread(t2).start();
        new Thread(t3).start();
    }
}

Lock以下功能是synchronized不具备的

ReentrantReadWriteLock:读写锁

private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
 
    private static int count = 1;
 
    public static void main(String[] args) {
        Runnable read = () -> {
            // 创建了一个读锁
            ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
            readLock.lock();
            try {
                Thread.sleep(2000);
                System.out.println("我在读数据:" + count);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                readLock.unlock();
            }
        };
        Runnable write = () -> {
            // 创建了一个写锁
            ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();
            writeLock.lock();
            try {
                Thread.sleep(2000);
                System.out.println("我在写数据:" + count++);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                writeLock.unlock();
            }
        };
        for (int i = 0; i < 100; i++) {
            Random random = new Random();
            int flag = random.nextInt(100);
            System.out.println("生成的随机整数:" + flag);
            if(flag > 20){
                new Thread(read).start();
            }else {
                new Thread(write).start();
            }
        }
    }
}

lock锁的原理cas和aqs

public class Ch06 {

   private static AtomicInteger adder = new AtomicInteger();

   public static void main(String[] args) throws InterruptedException {
       int a = 10;
       for (int i = 0; i < 1000; i++) {
           Thread thread = new Thread(() -> {
               adder.getAndIncrement();
           });
           thread.start();
           // 阻塞
           thread.join();
       }
       System.out.println("a:" + a);
       System.out.println("aaa:" + adder.get());
   }

线程池

为什么要使用线程池

JDK自带的四种线程池通过Executors提供的

  1. newCachedThreadPool:创建一个可缓存线程池,如果线程池长度超过处理需要,可以灵活回收空闲线程,若无可回收,创建新线程。
  2. newFixedThreadPool:创建一个定长的线程池,可以控制线程最大并发数,超出的线程会在队列中等待。
  3. newScheduledThreadPool:创建一个定长的线程池,支持定时及周期性任务执行
  4. newSingleThreadExecutor:创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有的任务按照指定顺序执行
  ThreadPoolExecutor(int corePoolSize,
                     int maximumPoolSize,
                     long keepAliveTime,
                     TimeUnit unit,
                     BlockingQueue<Runnable> workQueue,
                     ThreadFactory threadFactory,
                     RejectedExecutionHandler handler)

参数的意义(重要):

  1. corePoolSize:线程池里线程的数量,核心线程池大小
  2. maximumPoolSize:指定了线程池里的最大线程数量
  3. keepAliveTime:当线程池线程数量大于corePoolSize,多出来的空闲线程,多长时间被销毁
  4. unit:时间单位
  5. workQueue:任务队列,用于存放提交但是尚未被执行的任务
  6. threadFactory:线程工厂,用来创建线程,线程工厂就是我们new线程的
  7. handler:拒绝策略,是将任务添加到线程池中时,线程池拒绝该任务多采取的相应的措施。

常见的工作队列

线程池提供了四种拒绝策略:

  1. AbortPolicy:直接抛出异常,默认的策略。
  2. CallerRunPolicy:用调用者所在的线程来执行任务
  3. DiscardOldestPolicy:丢弃阻塞队列中最靠前的任务,并执行当前任务
  4. DiscardPolicy:直接丢弃任务
public class Ch01 {
 
    public static void main(String[] args) {
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
 
        Runnable taskOne = () -> {
            System.out.println(Thread.currentThread().getName() + "taskOne...");
        };
 
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
 
        ExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);
 
        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
 
        for (int i = 0; i < 40; i++) {
            fixedThreadPool.submit(taskOne);
        }
    }
}

自定义线程池

public class Ch02 {

   private static final AtomicInteger poolNumber = new AtomicInteger(1);

   private final ThreadGroup group;

   private final AtomicInteger threadNumber = new AtomicInteger(1);

   private final String namePrefix;

   Ch02(String name){
       SecurityManager s = System.getSecurityManager();
       group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();

       namePrefix = name + "-" + poolNumber.getAndIncrement() + "-thread-";
   }

   Ch02(){
       this("default");
   }
   public Thread newThread(Runnable r){
       // 就是在创建线程
       Thread t = new Thread(group,r,namePrefix + threadNumber.getAndIncrement(),0);

       if(t.isDaemon()){
           t.setDaemon(false);
       }
       if(t.getPriority() != Thread.NORM_PRIORITY){
           t.setPriority(Thread.NORM_PRIORITY);
       }
       return t;
   }
   public static void main(String[] args) {
       Ch02 ch02 = new Ch02();
       ch02.newThread(()->{
           System.out.println("自定义线程池创建的线程...");
       }).start();
   }

}

重点

  1. 创建线程的4种方式
  2. 线程同步(synchronized,ReentrantLock,ReentrantReadWriteLock)
  3. 线程之间的通信(wait,notify,notifyAll)
  4. 线程类的常用方法
  5. 指令重排,线程争抢,可见性,原子性,volatile关键字

标签:04,Thread,lock,08,线程,void,第五组,new,public
来源: https://www.cnblogs.com/laizhedong/p/16552425.html