多线程基础

发布时间 2023-07-13 23:31:26作者: record-100

1. 继承 Thread 类 重写 run 方法 启动调用 start 方法 缺点 不能继承其他类 优点简单

2. 定义任务类继承 Runnable 接口 实现 run 方法    MyRunable 为自定义的任务类  优点可以继承其他类 

Runnable t = new MyRunable();
new Thread(t).start();

3. JDK 5.0 提供了 Callable接口 和 FutureTask类来实现 优点 可以返回线程执行的结果 

 1. 创建任务对象
  定义一个类实现Callable接口,重写call方法,封装要做的事情,和要返回的数据。
  把 Callable类型的对象封装成FutureTask(线程任务对象)。
2.把线程任务对象交给Thread对象。
3.调用Thread对象的start方法启动线程。
4.线程执行完毕后,通过 FutureTask 对象的get方法获取线程任务执行结果。
Callable<String> t = new MyCallable();
FutureTask<String> task = new FutureTask<>(t);
Thread thread = new Thread(task);
thread.start();
String res = task.get();
System.out.println(res);

4. 线程同步(解决线程安全问题)

  让多个线程依次访问共享资源,这样就解决线程安全问题  加锁

  方式一:同步代码块(同步锁)

// 静态方法建议用类名作为锁
    public static void test() {

        synchronized (Account.class) {

        }
    }

    public void drawMoney(double money) {

        String threadName = Thread.currentThread().getName();

        // this正好代表共享资源 实例方法建议用this作为锁对象
        synchronized (this) {
            if (this.money >= money) {
                System.out.println(threadName + "来取了" + money + "元成功");
                this.money -= money;
                System.out.println(threadName +  "余额" + this.money);
            } else {
                System.out.println(threadName + "来取钱,钱不足");
            }
        }
    }

  方法二:同步方法

// 同步方法 实例方法 隐含用this作为锁
    public synchronized void drawMoney(double money) {

        String threadName = Thread.currentThread().getName();

        if (this.money >= money) {
            System.out.println(threadName + "来取了" + money + "元成功");
            this.money -= money;
            System.out.println(threadName +  "余额" + this.money);
        } else {
            System.out.println(threadName + "来取钱,钱不足");
        }

    }

  方式三:Lock锁

  Lock锁是JDK5开始提供的一个新的锁定操作,通过它可以创建出锁对象进行加锁和解锁,更灵活,更方便,更强大。

  Lock是接口,不能直接实例化,可以采用它的实现类 ReentrantLock 来构建 Lock 锁对象。

  

/**
     * 创建一个锁对象
     */
    private final Lock lk = new ReentrantLock();

    public void drawMoney(double money) {

        String threadName = Thread.currentThread().getName();

        try {
            // 加锁
            lk.lock();
            if (this.money >= money) {
                System.out.println(threadName + "来取了" + money + "元成功");
                this.money -= money;
                System.out.println(threadName +  "余额" + this.money);
            } else {
                System.out.println(threadName + "来取钱,钱不足");
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            // 解锁
            lk.unlock();
        }
    }

5. 线程通信

  当多个线程共同操作共享资源时,线程 间通过某种方式互相告诉自己的状态,以相互协调,并避免无效的资源争夺。

public class Test6 {

    public static void main(String[] args) {
        Desk desk = new Desk();

        // 三个生产者线程
        new Thread(() -> {
            while (true) {
                desk.put();
            }
        }, "厨师1").start();

        new Thread(() -> {
            while (true) {
                desk.put();
            }
        }, "厨师2").start();

        new Thread(() -> {
            while (true) {
                desk.put();
            }
        }, "厨师3").start();


        // 两个消费者线程
        new Thread(() -> {
            while (true) {
                desk.get();
            }
        }, "吃货1").start();

        new Thread(() -> {
            while (true) {
                desk.get();
            }
        }, "吃货2").start();

    }
}
public class Desk {

    private List<String> list = new ArrayList<>();

    // 放一个包子的方法
    // 厨师1 厨师2 厨师3
    public synchronized void put() {
        try {
            String name = Thread.currentThread().getName();
            // 判断是否有包子
            if (list.size() == 0) {
                list.add(name + "做的肉包子");
                System.out.println(name + "做了一个肉包子~~");
                Thread.sleep(2000);
                // 等待自己,唤醒别人 要使用当前锁对象
                this.notifyAll();
                this.wait();
            } else {
                // 等待自己,唤醒别人 要使用当前锁对象
                this.notifyAll();
                this.wait();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 吃货1 吃货2
    public synchronized void get() {

        try {
            String name = Thread.currentThread().getName();
            if (list.size() == 1) {
                // 有包子,吃了
                System.out.println(name + "吃了:" + list.get(0));
                list.clear();
                Thread.sleep(1000);
                this.notifyAll();
                this.wait();
            } else {
                // 没有包子
                this.notifyAll();
                this.wait();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}