线程笔记整理

进程是资源( CPU 内存 硬盘空间 )分配的基本单位

每个进程至少有一个线程, 线程是任务调度的基本单位

多线程中的概念

  并发: 同时发生了, 说明服务支持并发

  并行: 同时处理 (CPU通过高速切换任务实现)

  穿行: 按顺序进行

  同步: 一个任务的开始必须等待上一个任务的结束

  异步: 任务之间互不影响, 无需等待任务的反馈结果

线程的创建

1. 自定义一个类取继承Thread并重写run方法

public class CustomThread extends Thread {
    /**
     * run是线程真正执行的任务
     */
    @Override
    public void run() {
        for (int i = 0; i < 2000000000; i++) {
            System.out.println("threadA " + i);
        }
    }
}

 

//测试类
public class ThreadExercise {
    public static void main(String[] args) {
        CustomThread customThread = new CustomThread();
        //启动线程
        customThread.start();
    }
}

 

2. 实现接口Runnable

public static void createThread2() {
        System.out.println("main thread start");
        Thread threadA = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    System.out.println("threadA " + i);
                }
            }
        });

        Thread threadB = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                System.out.println("threadB " + i);
            }
        });
        threadA.start();
        threadB.start();
        System.out.println("main thread end");
    }

 

3. 实现接口Callbale, 线程执行完任务之后会返回一个结果, 使用到FuterTask

public static void createThread3() {
        // Callable接口是线程执行完之外之后 返回一个结果
        FutureTask<Object> futureTask = new FutureTask<>(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println("threadA " + i);
            }
            return "abc";
        });
        Thread threadA = new Thread(futureTask);
        threadA.start();
        try {
            //获取线程的返回结果 get是阻塞式的方法
            Object o = futureTask.get();
            System.out.println("return " + o);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println("main end ");
    }

 

线程的一些方法

 public static void threadMethods() {
        Thread thread = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                System.out.println(Thread.currentThread().getName() + i);
            }
        });
        //setName()设置线程名
        thread.setName("tom-threadA");
        //getState()方法获取线程当前状态
        System.out.println(thread.getState());
        // start()只是表示线程准备好了 可以被OS调度了
        thread.start();
        System.out.println(thread.getState());
        //getPriority获取线程的优先级 OS调度器会优先调度高优先级的线程
        System.out.println("priority: " + thread.getPriority());
        //getId()获取当前线程的ID
        System.out.println("id " + thread.getId());
        //currentThread() 获取当前线程
        Thread thread1 = Thread.currentThread();
        //getName()获取当前线程名
        System.out.println(thread1.getName());

        try {
            // 当前线程需要等待 thread执行完之后才能继续往下走
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(" main thread end");
    }    

 

线程池

  • 频繁的创建和销毁线程是在浪费资源, 线程池(里面有很多个线程)实现是对象池思想, 当有任务来的时候, 从线程池中取出一个线程来执行, 任务结束后回归线程池继续执行下一个任务
  • 线程池是为了节省系统空间, 提高性能
public static void threadPoolMethod() {
        // 频繁的创建和销毁线程 在浪费资源 线程池(很多个线程) 节省资源
        // 对象池思想 当有任务来的时候,取出一个线程来执行完任务,回归到池子接下一个任务
        // 创建了一个固定数量的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(2);//2
        // 带缓冲区的线程
        ExecutorService executorService1 = Executors.newCachedThreadPool(); //100
        //提交任务给池子
        executorService.submit(() -> {
            for (int i = 0; i < 100; i++) {
                System.out.println("threadA " + i);
            }
            System.out.println(Thread.currentThread().getId());
        });
        try {
            //单位是 毫秒 让线程休眠
//            Thread.sleep(1000L);
            TimeUnit.SECONDS.sleep(1L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        executorService.submit(() -> {
            for (int i = 0; i < 100; i++) {
                System.out.println("threadB " + i);
            }
            System.out.println(Thread.currentThread().getId());
            return "";
        });
        //关闭线程池
        executorService.shutdown();
    }

 

线程安全/线程同步

多线程环境下, 同时对内存/共享变量进行操作时会出现数据不一致的情况

public class BankAccount {
    private double balance;

    /**
     * 原子性
     * @param money
     */
    public void saveMoney(double money) {
        //1,当一个线程取出balance
        //2,另一个线程调用add方法
        //3,会进行重新赋值
            balance = balance + money;
    }
    public void withDraw(double money) {
            balance -= money;
    }
    public double getBalance() {
        return balance;
    }
}

 

//测试类
public static void main(String[] args) {
        BankAccount bankAccount = new BankAccount();
        Thread threadA = new Thread(() -> {
            for (int i = 0; i < 20000; i++) {
                bankAccount.saveMoney(10.0);
            }
            System.out.println("A end");
        });
        Thread threadB = new Thread(() -> {
            for (int i = 0; i < 20000; i++) {
                bankAccount.withDraw(10.0);
            }
            System.out.println("B end");
        });


        threadA.start();
        threadB.start();
        try {
            TimeUnit.SECONDS.sleep(1L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("余额 " + bankAccount.getBalance());
    }

 

如何解决?

1. synchronized表示线程同步

  • synchronized可以用在方法声明处, 方法内部(当前对象的锁), 用在静态方法中(需要当前类的锁)
  • 每个对象都有一把对象锁, 如果方法使用了synchronized进行修饰, 那么线程在执行方法的时候必须获取对象锁才能够去执行
  • synchronized保证了原子性(要么都做, 要么都不做)
  • synchronized是一把排它锁/互斥锁, 并且是可重入锁(不需要重复获取)
  • synchronized在使用的时候如果出现异常会自动释放锁

 

 /**
     * 原子性
     *
     * @param money
     */
    public void saveMoney(double money) {
        //1,取出balance
        //2,add
        //3,重新赋值
        // 小括号 里面表示需要获取 哪个对象的对象锁
        synchronized (this) {// 需要获取当前对象的对象锁
            balance = balance + money;
        }
    }


    public synchronized void withDraw(double money) {
        balance -= money;
    }


    /**
     * 静态方法需要是类锁 字节码对象的锁
     */
    public static void test() {
        synchronized (BankAccount.class) {
            System.out.println(" =");
        }
    }

 

2. 使用Lock, 上锁和释放锁的时机由使用者进行把控

注意: 释放锁放在finally中做, 防止出现死锁

public class BankAccount {
    private double balance;
    //创建了一把可重入锁
    private ReentrantLock lock = new ReentrantLock();
    /**
     * @param money
     */
    public void saveMoney(double money) {
        //上锁
        lock.lock();
        try {
            balance = balance + money;
            System.out.println(1 / 0);
        } catch (Exception e) {
        } finally {
            //释放锁
            lock.unlock();
        }
    }
 }

 

线程安全的类

1. 类内部做了线程保护, 例如集合中类Vector , Hashtable

 public static void main(String[] args) {
        Vector<Integer> arrayList = new Vector<>();
        Thread threadA = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                arrayList.add(i);
            }
        });
        Thread threadB = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                arrayList.add(i);
            }
        });
        threadA.start();
        threadB.start();
        try {
            TimeUnit.SECONDS.sleep(5L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("size " + arrayList.size());
    }

 

2. 原子类Atomic**内部使用CAS(Conpare And Swap)保证数据一致性

public class DeadLockExercise {
    //    private static int count = 0;
    private static AtomicInteger count = new AtomicInteger(0);
    static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        safeMethod();
    }
    public static void safeMethod() {
        int a = 1;
        Thread threadA = new Thread(() -> {
            for (int i = 0; i < 1000000; i++) {
                count.incrementAndGet();
            }
            System.out.println("A end");
        });
        Thread threadB = new Thread(() -> {
            for (int i = 0; i < 1000000; i++) {
                count.decrementAndGet();
            }
            System.out.println("B end");
        });
        threadA.start();
        threadB.start();
        try {
            TimeUnit.SECONDS.sleep(1L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(" count " + count);
    }
}

 

死锁

  • 当多个线程之间出现互相等待的情况, 会产生死锁

如何解决死锁

  • synchronized嵌套锁的时候, 上锁的顺序虚保持一致
  • 使用Lock进行获取锁的时候用tryLock, 如果拿不到锁直接返回; 或者加一个超时等待
//synchronized死锁
public static void deadLockMethod(){
        Object o1 = new Object();
        Object o2 = new Object();

        Thread threadA = new Thread(() -> {
            synchronized (o1) {
                System.out.println("threadA 获取了object1的对象锁");
                synchronized (o2) {
                    System.out.println("threadA 获取了object2的对象锁");
                }
            }
        });
        Thread threadB = new Thread(() -> {
            synchronized (o2) {
                System.out.println("threadB 获取了object2的对象锁");
                synchronized (o1) {
                    System.out.println("threadB 获取了object1的对象锁");
                }
            }
        });
    }

 

使用lock的tryLock解决

   public static void deadLockMethod1() {
        ReentrantLock lock1 = new ReentrantLock();
        ReentrantLock lock2 = new ReentrantLock();
       

        Thread threadA = new Thread(() -> {
            // tryLock()不会无限等待 获取不到锁 直接返回false
            try {
//                当获取锁时,锁资源在超时时间之内变为可用,并且在等待时没有被中断,那么当前线程成功获取锁,返回true,同时当前线程持有锁的count设置为1.
                if (lock1.tryLock(3, TimeUnit.SECONDS)) {
                    System.out.println("threadA 获取object1的锁");
                    TimeUnit.MILLISECONDS.sleep(100L);
//                    当获取锁时,如果其他线程持有该锁,无可用锁资源,直接返回false,这时候线程不用阻塞等待,可以先去做其他事情
                    if (lock2.tryLock()) {
                        try {
                            System.out.println("threadA 获取了object2的对象锁");
                            System.out.println("===");
                        } finally {
                            lock2.unlock();
                        }
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock1.unlock();
            }
        });
        Thread threadB = new Thread(() -> {
            if (lock2.tryLock()) {
                try {
                    System.out.println("threadB 获取object2的锁");
                    TimeUnit.MILLISECONDS.sleep(100L);
                    if (lock1.tryLock()) {
                        try {
                            System.out.println("threadB 获取了object1的对象锁");
                            System.out.println("===");
                        } finally {
                            lock1.unlock();
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock2.unlock();
                }
            }
        });
        threadA.start();
        threadB.start();
    }

 生产者消费者

  • wait()方法和notify()notifyAll()必须在同步代码块中使用
  • wait()方法应该始终出现在循环中, 唤醒之后继续判断条件; 导致当前线程进入到当前线程的等待池里面
  • notifyAll()通知当前对象等待池中的所有线程 , notify()通知当前对象等待池中某个线程

 

//仓库类
public class Store {
    //商品数据量
    private int count;
    //仓库最大容量
    private final int MAX_COUNT = 200;

    /**
     * 生成者生成商品进去
     */
    public void put() {
        synchronized (this) {
            while (count == MAX_COUNT) {
                System.out.println("仓库已经满了 停止生产");
                try {
                    //需要等待 消费者来消费了 导致当前线程进入到当前对象的等待池里面
                    // wait()方法 线程会释放锁 sleep()是不释放锁的
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            count++;
            System.out.println("生产者生产了一件商品 " + count);
            //notifyAll 通知当前对象等待池中的所有线程,notify()通知当前对象等待池中某个线程
            this.notifyAll();
        }
    }

    /**
     * 消费者去商品
     */
    public void get() {
        synchronized (this) {
            while (count == 0) {
                System.out.println("仓库已经空了 停止消费 需要等待");
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            count--;
            System.out.println("消费者消费了一件商品 " + count);
            //通知 等待池中的生产者线程
            this.notifyAll();
        }
    }
}
//测试类
public class StoreTest {
    public static void main(String[] args) {
        Store store = new Store();

        Thread threadA = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                store.put();
            }
        });

        Thread threadB = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                store.get();
            }
        });
        threadA.start();
        threadB.start();
    }
}

 

 sleep()和wait()的区别

  1. sleep()是Thread的静态方法, wait()是Object的方法
  2. 使用不同, sleep()可以在任意地方使用, wait()只能在同步代码块中调用
  3. 关于锁的释放, sleep()不会释放锁, wait()会释放锁

多线程3个核心概念

1.原子性

  要么全都执行, 要么全都不执

   synchronized保证原子性

2. 可见性, 线程之间的可见性

  线程A对共享变量的操作, 其他线程可见(必须从主存获取最新的值)

  synchronized可以保证可见性

  volatile也可以保证可见性

 3. 顺序性 

  指令执行的顺序

  JVM内部有指令重排序, 是为了性能; 在单线程情况下, 不会有任何问题

  多线程情况下, 有可能有问题

  volatile可以禁止JVM指令重排序 

public class VisibleExercise {
    // volatile可以保证可见性
    private volatile static boolean flag = true;

    public static void main(String[] args) {
        new Thread(() -> {
            while (flag) {
            }
        }).start();

        try {
            TimeUnit.SECONDS.sleep(1L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        flag = false;
        System.out.println("main end");
    }
}

 

设计模式

  设计模式( Design Pattern )是前辈们对代码开发经验的总结, 是解决特定问题的一系列套路, 他不是语法规定, 而是一套用来提高代码可复用性, 可维护性, 可读性, 稳健型以及安全性的解决方案

单利模式

只有一个实例, 后期Servlet都是单例模式, 以及SpringMVC中的controller等; 管理器或者控制器都是单例的

核心思路:

  1. 构造器私有化
  2. 提供一个和本类类型一样的静态成员变量
  3. 提供一个静态的共有方法, 返回类型是本类类型

恶汉式单例

缺点: 可能存在空间浪费

优点: 在类加载期间实例化, 线程安全

使用场景:单例占用内存小的时候

public class Singleton {
    private static Singleton instance = new Singleton();
    private Singleton() {
    }

    public static Singleton getInstance() {
        return instance;
    }
}

 

懒汉式单例

缺点: 需要外部加线程保护

优点: 空间合理使用

使用场景: 单例对象是一个大对象

public class LazySingleton {
    private static LazySingleton instance;
    private LazySingleton() {
    }
    /**
     * 第一次请求的时候 实例化
     * JVM指令重排序会导致对象状态出错,
     * @return
     */
    public static LazySingleton getInstance() {
        if (instance == null) {
            synchronized (LazySingleton.class) {
                //double check双重检测
                if (instance == null) {
                    instance = new LazySingleton();
                }
            }
        }
        return instance;
    }
}
//防止指令重排序
public class LazySingleton {
    private volatile static LazySingleton instance;

    private LazySingleton() {
    }

    /**
     * 第一次请求的时候 实例化
     * JVM指令重排序会导致  对象状态出错,
     *
     * @return
     */
    public static LazySingleton getInstance() {
        if (instance == null) {
            synchronized (LazySingleton.class) {
                //double check双重检测
                if (instance == null) {
                    /**
                     * 1,开辟空间 10ms
                     * 2,初始化实例 100ms
                     * 3,引用赋值 5ms     115ms  13 2 15ms
                     */
                    instance = new LazySingleton();
                }
            }
        }
        return instance;
    }
}

 

posted @ 2021-04-22 00:16  小_Leo  阅读(75)  评论(0)    收藏  举报