Java多线程基础

该文章基于狂神的Java多线程详解

一、概念

程序

程序是指令和数据的有序集合,是一个静态的概念。

进程

进程是程序的一次执行过程,是一个动态的概念,是系统资源分配和调度的独立单位。

线程

线程是进程的一个实体,是 CPU 调度和分派的基本单位,每一个进程中都至少有一个线程。

  • 线程分为用户线程守护线程
  • 守护线程是指在程序运行的时候在后台提供一种通用服务的线程。

并发

指在同一时刻,有多条指令在多个处理器上同时执行。所以无论从微观还是从宏观来看,二者都是一起执行的。需要多处理器

并行

指在同一时刻只能有一条指令执行,但多个进程指令被快速的轮换执行,使得在宏观上具有多个进程同时执行的效果,但在微观上并不是同时执行的,只是把时间分成若干段,使多个进程快速交替的执行。仅在一个处理器上就可以。

二、创建线程的三种方式

方式一:继承Thread类

步骤

  • 写一个类继承Thread类,并重写run方法
  • 创建该类对象
  • 调用该对象的start方法

代码演示

public class MyThread {
    public static void main(String[] args) {
    	//多态
        Thread thread = new Thread1();
        thread.start();
    }
}

class Thread1 extends Thread {
    @Override
    public void run() {
        System.out.println("我是新方法");
    }
}

结果

在这里插入图片描述

方式二:实现Runnable接口

步骤

  • 写一个类实现Runnable接口,并重写run方法
  • 创建该类对象
  • 创建代理该类对象的Thread类对象(点这里看静态代理模式
  • 调用该对象的start()方法

注:这几步可以直接使用lamda表达式简化。

代码演示

public class MyRunnable {
    public static void main(String[] args) {
        Runnable r = new Runnable1();
        Thread thread = new Thread(r);
        thread.start();

        //lamda表达式
        new Thread(() -> {
            System.out.println("我是lamda表达式创建的新线程");
        }).start();
    }
}

class Runnable1 implements Runnable {
    @Override
    public void run() {
        System.out.println("我是传统方式创建的新线程");
    }
}

结果

在这里插入图片描述

方式三:实现Callable接口

步骤

  • 写一个类实现Callable接口,并重写call()方法
  • 创建该类对象
  • 创建执行服务
  • 提交执行
  • 获取结果(会阻塞,可不调用)
  • 关闭服务

代码演示

public class MyCallable {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Callable c1 = new Callable1();
        Callable c2 = new Callable1();

        //创建执行服务
        ExecutorService service = Executors.newFixedThreadPool(2);

        //提交执行
        Future<Boolean> r1 = service.submit(c1);
        Future<Boolean> r2 = service.submit(c2);

        //获取结果
        boolean rs1 = r1.get();
        boolean rs2 = r2.get();
        System.out.println(rs1);
        System.out.println(rs2);

        //关闭服务
        service.shutdownNow();
    }
}

class Callable1 implements Callable<Boolean> {
    @Override
    public Boolean call() throws Exception {
        System.out.println("我是被创建的一个新线程");
        return true;
    }
}

结果

在这里插入图片描述

三、线程的五个状态

在这里插入图片描述

四、线程常用的操作方法

停止线程

  • 不推荐JDK提供的stop()、destory()方法(已废弃)。
  • 推荐线程自己停止。
  • 建议使用标志位进行终止。
    代码:
/**
 * 测试线程停止方法
 * @author 王子龙
 * @date Created in 2020/8/12 10:30
 */
public class StopTest {
    public static void main(String[] args) throws InterruptedException {
        ThreadStop r = new ThreadStop();
        System.out.println("主线程运行中...");
        new Thread(r).start();
        Thread.sleep(10);
        System.out.println("主线程操作线程停止!");
        r.stop();
    }
}

class ThreadStop implements Runnable {
    boolean flag = true;
    @Override
    public void run() {
        while (flag) {
            System.out.println("线程运行中...");
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("线程结束!");
    }
    //自定义停止方法
    public void stop() {
        flag = false;
    }
}

结果:
在这里插入图片描述

线程休眠

  • sleep(time)指定当前线程阻塞的毫秒数。
  • sleep存在异常InterruptedException。
  • sleep时间结束后线程进入就绪状态。
  • 每个对象都有一把锁,sleep不会释放锁。

代码:

/**
 * 测试sleep
 * @author 王子龙
 * @date Created in 2020/8/12 10:48
 */
public class SleepTest {
    public static void main(String[] args) {
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println(new Timestamp(System.currentTimeMillis()));
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

结果:
在这里插入图片描述

线程礼让

  • 礼让线程,让当前正在执行的线程暂停,但不阻塞。
  • 让当前线程从运行状态转为就绪状态。
  • 让cpu重新调度(有可能再次调度到该线程)。

代码:

/**
 * 测试yield
 * @author 王子龙
 * @date Created in 2020/8/12 10:55
 */
public class YieldTest {
    public static void main(String[] args) {
        new Thread(()->{
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < 10; i++) {
                Thread.yield();
                System.out.println("我是线程1,这是我的第" + (i + 1) + "次执行!");
            }
        }).start();

        new Thread(()->{
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < 10; i++) {
                System.out.println("我是线程2,这是我的第" + (i + 1) + "次执行!");
            }
        }).start();
    }
}

结果:
在这里插入图片描述
运行多次,每次线程一都是比线程二晚结束。而去掉yield()后,两个线程谁晚结束都有可能。

线程插队

  • join会阻塞当前进程,等待插队的线程执行完之后才会执行当前线程。

代码:

/**
 * 测试Join
 * @author 王子龙
 * @date Created in 2020/8/12 11:06
 */
public class JoinTest {
    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println("我是VIP线程,这是我的第" + (i + 1) + "次执行!");
            }
        });

        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println("我是线程2,这是我的第" + (i + 1) + "次执行!");
                if (i == 5) {
                    thread1.start();
                    try {
                        thread1.join();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread2.start();
    }
}

结果:
在这里插入图片描述

观测线程状态

  • 进入TERMINATED(死亡状态)的线程不能再次启动。

代码:

/**
 * 观测线程状态
 * @author 王子龙
 * @date Created in 2020/8/12 11:16
 */
public class StateTest {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        System.out.println("//");
        System.out.println(t.getState());
        t.start();
        while(!t.getState().equals(Thread.State.TERMINATED)) {
            System.out.println(t.getState());
            Thread.sleep(100);
        }
        System.out.println(t.getState());
        System.out.println("//");
    }
}

结果:
在这里插入图片描述

线程优先级

  • Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行。
  • 线程的优先级用数字表示,范围从1~10:
    • Thread.MIN_PRIORITY = 1;
    • Thread.MAX_PRIORITY = 10;
    • Thread.NORM_PRIORITY = 5;
  • 使用以下方式改变或获取优先级:
    • getPriority() setPriority(int)。
  • 优先级的设定建议在start()前。
  • 优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用了,这些都是取决于CPU的调度。

代码:

/**
 * 测试优先级的函数
 * @author 王子龙
 * @date Created in 2020/8/12 13:45
 */
public class PriorityTest {
    public static void main(String[] args) {
        //主线程默认优先级
        System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().getPriority());
        Thread t1 = new Thread(new MyPriority());
        Thread t2 = new Thread(new MyPriority());
        Thread t3 = new Thread(new MyPriority());
        Thread t4 = new Thread(new MyPriority());

        //更改优先级
        t1.setPriority(1);
        t2.setPriority(4);
        t3.setPriority(7);
        t4.setPriority(10);

        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}

class MyPriority implements Runnable {
    @Override
    public void run() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+ ":" + Thread.currentThread().getPriority());
    }
}

结果:
在这里插入图片描述

设置守护线程

  • 虚拟机必须确保用户线程执行完毕,而不用等待守护线程执行完毕。
  • Java默认创建的线程为用户线程

代码:

/**
 * 测试守护线程
 * @author 王子龙
 * @date Created in 2020/8/12 13:58
 */
public class DaemonTest {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("守护线程;我一直在!");
            }
        });

        //设置守护线程
        thread.setDaemon(true);
        thread.start();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("用户线程:我正在运行!");
            }
            System.out.println("用户线程:我无了!");
        }).start();
    }
}

结果:
在这里插入图片描述

五、线程同步

  • 队列+锁实现线程同步,线程队列实现等待线程有顺序,锁保证当前线程对数据的操作是安全的。
  • 由于同一线程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突问题,为了保证数据在方法中被访问时的正确性,咋访问时加入锁机制synchronized,当一个线程获得对象的排它锁、独占资源,其它线程必须等待,使用后释放锁。该方法存在以下问题
    • 一个线程持有锁会导致其他所有需要此锁的线程挂起。
    • 在多线程竞争下,加锁,释放锁会导致较多的上下文切换调度延时,引起性能问题。
    • 如果一个优先级高的线程等待一个优先级低的线程释放锁,会导致优先级倒置,引起性能问题。

不安全的三个案例

多个线程代理同一个Runnable对象操作相同的数据

代码:

/**
 * 抢票的不安全案例:多个线程代理同一个Runnable对象操作相同的数据
 * @author 王子龙
 * @date Created in 2020/8/12 14:18
 */
public class TicketTest {
    public static void main(String[] args) {
        Runnable r = new Ticket();

        new Thread(r,"张三").start();
        new Thread(r,"李四").start();
        new Thread(r,"王五").start();
    }
    }

class Ticket implements Runnable {
    private int tickets = 10;
    @Override
    public void run() {
        while (tickets > 0) {
            buy();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void buy() {
        if (tickets > 0) {
            System.out.println(Thread.currentThread().getName() + "抢到了一张票,还剩" + --tickets + "张票");
        }
    }
}

结果:
在这里插入图片描述

结论: 出现了非法操作,多个人同时购买同一张票。

多个线程代理不同Runnable对象或者本身是不同Thread子类对象操作相同的数据

代码:

/**
 * 取钱的不安全案例:多个线程调用代理不同Runnable对象或者是不同Thread对象操作同一个数据
 * @author 王子龙
 * @date Created in 2020/8/12 14:35
 */
public class CountTest {
    public static void main(String[] args) {
        Account account = new Account(100);
        Runnable r1 = new Withdraw(account, 50, 0);
        Runnable r2 = new Withdraw(account, 100, 0);

        new Thread(r1,"王一").start();
        new Thread(r2,"李二").start();
    }
}

class Withdraw implements Runnable {
    //账户
    private Account account;
    //需要取的钱
    private int withdraw;
    //身上的钱
    private int nowMoney;

    Withdraw(Account account, int withdraw, int nowMoney) {
        this.account = account;
        this.withdraw = withdraw;
        this.nowMoney = nowMoney;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        while (account.withdraw(withdraw)) {
            nowMoney += withdraw;
            System.out.println(Thread.currentThread().getName() + "取到了" + withdraw + "的钱,身上还有" + nowMoney);
        }
        System.out.println(Thread.currentThread().getName() + "无法取钱" + withdraw + ",账户里只有" + account.getMoney());
    }
}

//账户
class Account {
    private int money;

    Account(int money) {
        this.money = money;
    }

    public boolean withdraw(int withdraw) {
        if (money >= withdraw) {
            money -= withdraw;
            return true;
        } else {
            return false;
        }
    }

    public int getMoney() {
        return money;
    }
}

结果:
在这里插入图片描述

结论: 出现了非法操作,有人同时取到了更多的钱。

对线程不安全的集合进行多线程操作

代码:

/**
 * 集合的不安全案例:对线程不安全的集合进行多线程操作
 * @author 王子龙
 * @date Created in 2020/8/12 15:10
 */
public class ArrayTest {
    public static void main(String[] args) throws InterruptedException {
        List<Integer> list = new ArrayList<>();

        new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                list.add(1);
            }
        }).start();
        new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                list.add(1);
            }
        }).start();
        new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                list.add(1);
            }
        }).start();
        new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                list.add(1);
            }
        }).start();
        new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                list.add(1);
            }
        }).start();
        new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                list.add(1);
            }
        }).start();
        Thread.sleep(2000);
        System.out.println(list.size());
    }
}

结果:
在这里插入图片描述

结论: 多个线程同时操作不安全集合时,导致数据出现丢失的情况。

同步方法和同步块

  • 由于Java的封装性,我们只需要针对方法来提出一套同步机制,这个机制就是synchronized关键字,它包含synchronized方法synchronized代码块两种用法。
  • 同步方法: synchronized方法控制对“对象”的访问,每个对象对应一把锁,每个synchronized方法都必须获得调用该方法的对象的锁才能执行,否则线程会阻塞,方法一旦执行,就独占该锁,直到该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行。
  • synchronized方法缺陷:如果将一个大的放方法申明为synchronized将会影响效率。
  • 同步块: synchronized(obj),其中obj被称之为同步监视器
  • synchronized方法无需指定同步监视器,因为同步方法的同步监视器就是调用该方法的对象,而不一定是进行数据操作的对象。而同步快可以选择同步监视器为进行数据操作的对象。
  • 同步监视器的执行过程:
    • 第一个线程访问,锁住同步监视器,执行其中代码。
    • 第二个线程访问,发现同步监视器被锁定,无法访问。
    • 第一个线程访问完毕,解锁同步监视器。
    • 第二个线程访问,发现同步监视器没有锁,然后锁定并访问。

利用同步方法和同步块解决三个不安全问题

多个线程代理同一个Runnable对象操作相同的数据

思路: 在购买方法上增加锁,每次线程操作时都锁住同一个runnable对象。
代码:

/**
 * 抢票的不安全案例:多个线程代理同一个Runnable对象操作相同的数据
 * @author 王子龙
 * @date Created in 2020/8/12 14:18
 */
public class TicketTest {
    public static void main(String[] args) {
        Runnable r = new Ticket();

        new Thread(r,"张三").start();
        new Thread(r,"李四").start();
        new Thread(r,"王五").start();
    }
    }

class Ticket implements Runnable {
    private int tickets = 10;
    @Override
    public void run() {
        while (tickets > 0) {
            buy();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

	//在购买方法上增加锁
    public synchronized void buy() {
        if (tickets > 0) {
            System.out.println(Thread.currentThread().getName() + "抢到了一张票,还剩" + --tickets + "张票");
        }
    }
}

结果:
在这里插入图片描述

多个线程代理不同Runnable对象或者本身是不同Thread子类对象操作相同的数据

思路: 在操作账户的代码块中设置同步块,锁定账户。
代码:

/**
 * 取钱的不安全案例:多个线程调用代理不同Runnable对象或者是不同Thread对象操作同一个数据
 * @author 王子龙
 * @date Created in 2020/8/12 14:35
 */
public class CountTest {
    public static void main(String[] args) {
        Account account = new Account(100);
        Runnable r1 = new Withdraw(account, 50, 0);
        Runnable r2 = new Withdraw(account, 100, 0);

        new Thread(r1,"王一").start();
        new Thread(r2,"李二").start();
    }
}

class Withdraw implements Runnable {
    //账户
    private Account account;
    //需要取的钱
    private int withdraw;
    //身上的钱
    private int nowMoney;

    Withdraw(Account account, int withdraw, int nowMoney) {
        this.account = account;
        this.withdraw = withdraw;
        this.nowMoney = nowMoney;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //对操作account的代码块进行锁住,对象是account
        synchronized (account) {
            while (account.withdraw(withdraw)) {
                nowMoney += withdraw;
                System.out.println(Thread.currentThread().getName() + "取到了" + withdraw + "的钱,身上还有" + nowMoney);
            }
            System.out.println(Thread.currentThread().getName() + "无法取钱" + withdraw + ",账户里只有" + account.getMoney());
        }
    }
}

//账户
class Account {
    private int money;

    Account(int money) {
        this.money = money;
    }

    public boolean withdraw(int withdraw) {
        if (money >= withdraw) {
            money -= withdraw;
            return true;
        } else {
            return false;
        }
    }

    public int getMoney() {
        return money;
    }
}

结果:
在这里插入图片描述

对线程不安全的集合进行多线程操作

思路: 使用JUC包下的线程安全的集合来进行多线程操作
代码:

/**
 * 集合的不安全案例:对线程不安全的集合进行多线程操作
 * @author 王子龙
 * @date Created in 2020/8/12 15:10
 */
public class ArrayTest {
    public static void main(String[] args) throws InterruptedException {
    	//使用线程安全的集合
        List<Integer> list = new CopyOnWriteArrayList();


        new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                list.add(1);
            }
        }).start();
        new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                list.add(1);
            }
        }).start();
        new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                list.add(1);
            }
        }).start();
        new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                list.add(1);
            }
        }).start();
        new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                list.add(1);
            }
        }).start();
        new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                list.add(1);
            }
        }).start();
        Thread.sleep(2000);
        System.out.println(list.size());
    }
}

结果:
在这里插入图片描述

死锁

概念

所谓死锁是指多个线程因竞争资源而造成的一种僵局(互相等待),若无外力作用,这些进程都将无法向前推进。

形成死锁的四个必要条件

产生死锁必须同时满足以下四个条件,只要其中任一条件不成立,死锁就不会发生:

  • 互斥: 进程要求对所分配的资源进行排他性控制,此时若有其他进程请求该资源,则请求进程只能等待。
  • 不剥夺: 资源只能由获得该资源的进程自己来释放(只能是主动释放)。
  • 请求和保持: 进程已经保持了至少一个资源,但又提出了新的资源请求,而该资源 已被其他进程占有,此时请求进程被阻塞,但对自己已获得的资源保持不放。
  • 循环等待: 存在一种进程资源的循环等待链,链中每一个进程已获得的资源同时被 链中下一个进程所请求。

代码演示

代码:

/**
 * 死锁
 * @author 王子龙
 * @date Created in 2020/8/12 16:14
 */
public class LockDeadTest {
    private static final String mirror = "镜子";
    private static final String lipstick = "口红";
    public static void main(String[] args) {
        makeup(mirror, lipstick);
        makeup(lipstick, mirror);
    }

    private static void makeup(String thing1, String thing2) {
        new Thread(() -> {
            synchronized (thing1) {
                System.out.println(Thread.currentThread().getName() + "得到了" + thing1);
                synchronized (thing2) {
                    System.out.println(Thread.currentThread().getName() + "得到了" + thing2);
                }
            }
        }).start();
    }
}

结果:
在这里插入图片描述

lock锁

  • 从JDK5开始,Java提供了更强大的线程同步机制——通过显式定义同步锁对象来实现同步。同步锁使用Lock对象充当。
  • java.util.concurrent.locks.Lock接口是控制多个线程对共享资源进行独占访问,每次只能有一个线程对Lock对象加锁,线程开始访问共享资源之前应该先获得Lock对象。
  • ReentrantLock类实现了Lock,它拥有与synchronized相同的并发性和内存语义,在实现线程安全的控制中,比较常用的是ReentrantLock,可以显式的加锁、释放锁。
  • 需要同一个锁对象才能锁住。

代码示例

代码:

/**
 * 测试锁
 * @author 王子龙
 * @date Created in 2020/8/12 16:34
 */
public class LockTest {
    public static void main(String[] args) {
        new Thread(new LockThread()).start();
        new Thread(new LockThread()).start();
        new Thread(new LockThread()).start();
    }
}

class LockThread implements Runnable {
    private static int num = 10;
    private static final Lock LOCK = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            try {
                //加锁
                LOCK.lock();
                if (num > 0) {
                    System.out.println(Thread.currentThread().getName() + ":" +num--);
                } else {
                    break;
                }
            } finally { //进行解锁
                LOCK.unlock();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

结果:
在这里插入图片描述

synchronized与Lock的对比

  • Lock是显式锁(手动开启和关闭),synchronized是隐式锁,出了作用域自动释放。
  • Lock只有代码块锁,synchronized有代码块锁和方法锁。
  • 使用Lock锁,JVM将花费较少时间来调度线程,性能更好。并且有更好的扩展性(提供更多子类)。
  • 优先使用顺序:Lock > 同步代码块(已经进入了方法体,分配了相应资源) > 同步方法(在方法体之外)。

六、线程通信

Java提供的几个线程通信方法

wait

  • wait():表示线程一直等待,直到其他线程通知,与sleep不同,会释放锁
  • wait(long timeout):等待指定的毫秒数。
  • 注意:均是Object的方法,都只能在同步方法或者同步代码块中使用,否则便会抛出异常IllegalMonitorStateException

notify

  • notify():唤醒一个处于等待状态的线程。
  • notifyAll():唤醒同一个对象上所有调用wait方法的线程,优先级别高的线程优先调度。
  • 注意:均是Object的方法,都只能在同步方法或者同步代码块中使用,否则便会抛出异常IllegalMonitorStateException

生产者消费者问题

问题描述

  • 假设仓库中智能存放一件产品,生产者将生产出来的产品放入仓库,消费者将仓库中的产品取走消费。
  • 如果仓库中没有产品,则生产者将产品放入仓库,否则停止生产并等待,直到仓库中的产品都被消费者取走为止。
  • 如果仓库中放有产品,则消费者可以将产品取走消费,否则停止消费并等待,直到仓库中再次放入产品为止。

管程法

思路: 利用缓冲区将生产者和消费者分开。
代码:

/**
 * 管程法解决生产者消费者问题
 * @author 王子龙
 * @date Created in 2020/8/12 17:17
 */
public class Solution1 {
    public static void main(String[] args) throws InterruptedException {
        Buffer buffer = new Buffer();
        new Thread(new Productor(buffer)).start();
        Thread.sleep(400);
        new Thread(new Consumer(buffer)).start();
    }
}

//生产者
class Productor implements Runnable {
    private Buffer buffer;

    Productor(Buffer buffer) {
        this.buffer = buffer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            try {
                buffer.push(new Product(i));
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}

//消费者
class Consumer implements Runnable {
    private Buffer buffer;

    Consumer(Buffer buffer) {
        this.buffer = buffer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            try {
                buffer.pop();
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}

//产品
class Product {
    int id;
    public Product(int id) {
        this.id = id;
    }
}

//缓冲区
class Buffer {
    //容器
    Product[] products = new Product[10];
    //容器计数器
    int count = 0;

    //生产者放入产品
    public synchronized void push(Product product) throws InterruptedException {
        if (count == products.length) {//满了就等待并叫醒消费者消费
            System.out.println("缓冲区咋满了?快来消费!");
            wait();
        }
        //没满就生产
        products[count++] = product;
        System.out.println("在缓冲区第" + (count - 1) + "位生产了id为" + products[count - 1].id + "的产品");
        notifyAll();
    }

    //消费者消费产品
    public synchronized void pop() throws InterruptedException {
        if (count == 0) {//空了就等待并叫醒生产者生产
            System.out.println("缓冲区咋空了?快来生产!");
            wait();
        }
        count--;
        System.out.println("在缓冲区第" + (count) + "位消费了id为" + products[count].id + "的产品");
        notifyAll();
    }
}

结果:
在这里插入图片描述

信号灯法

思路: 通过一个共享信号来沟通线程。
代码:

/**
 * 信号灯法解决生产者消费者问题
 * @author 王子龙
 * @date Created in 2020/8/12 17:45
 */
public class Solution2 {
    public static void main(String[] args) throws InterruptedException {
        TV tv = new TV();
        new Thread(new Actor(tv)).start();
        Thread.sleep(400);
        new Thread(new Audience(tv)).start();
    }
}

//演员
class Actor implements Runnable {
    private TV tv;

    Actor(TV tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            try {
                tv.act("节目" + i);
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}

//观众
class Audience implements Runnable {
    private TV tv;

    Audience(TV tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            try {
                tv.watch();
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}

//电视
class TV {
    //节目
    String show;
    //是否有节目
    boolean flag = false;

    //表演者表演节目
    public synchronized void act(String string) throws InterruptedException {
        if (flag) { //有节目就休息
            System.out.println("有节目,演员休息会!");
            wait();
        }

        //没有节目就表演节目
        flag = true;
        show = string;
        System.out.println("演员表演了" + show);
        notifyAll();
    }

    //观众看节目
    public synchronized void watch() throws InterruptedException {
        if (!flag) { //没有节目就休息
            System.out.println("没有节目,观众休息会!");
            wait();
        }

        //有节目就观看节目
        flag = false;
        System.out.println("观众观看了" + show);
        notifyAll();
    }
}

结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值