【JAVA】【多线程】多线程学习笔记

实现thread

用 thread 实现线程

  1. 继承thread
  2. 重写run()(执行run是单线程)
  3. 创建线程对象,start()启动(start是并发执行)

线程开启不一定立即执行,由cpu调度


实现 runnable 接口(推荐)

  1. 定义类实现 Runnable 接口
  2. 重写run()
  3. 创建线程对象,start()启动
public class TestThread2 implements Runnable{
    private String url;
    private String name;
    
    public TestThread2 (String url, String name) {
        this.url = url;
        this.name = name;
    }

    @Override
    public void run() {
        TestThread2.WebDownloader webDownloader = new TestThread2.WebDownloader();
        webDownloader.downloader(url, name);
    }

    public static void main(String[] args) {
        TestThread2 t1 = new TestThread2("url1", "name1");
        TestThread2 t2 = new TestThread2("url2", "name2");
        TestThread2 t3 = new TestThread2("url3", "name3");
        new Thread(t1).start();
        new Thread(t2).start();
        new Thread(t3).start();
    }
}

避免单继承局限性,灵活方便,方便同一个对象被多个线程使用


实现Callable接口

  1. 重写Callable接口,需要返回值类型
  2. 重写call方法,需要抛出异常
  3. 创建线程对象
  4. 创建执行服务
  5. 提交执行
  6. 获取结果
  7. 关闭服务
import java.util.concurrent.*;

// 1.重写Callable接口,需要返回值类型
public class TestCallable implements Callable<Boolean> {
    private String url;
    private String name;

    public TestCallable(String url, String name) {
        this.url = url;
        this.name = name;
    }

    // 2.重写call方法,需要抛出异常
    @Override
    public Boolean call() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url, name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 3.创建线程对象
        TestCallable t1 = new TestCallable("url1", "name1");
        TestCallable t2 = new TestCallable("url2", "name2");
        TestCallable t3 = new TestCallable("url3", "name3");
        // 4.创建执行服务
        ExecutorService ser = Executor.newFixedThreadPool(3);
        // 5.提交执行
        Future<Boolean> r1 = ser.submit(t1);
        Future<Boolean> r2 = ser.submit(t2);
        Future<Boolean> r3 = ser.submit(t3);
        // 6.获取结果
        boolean ret1 = (r1).get();
        boolean ret2 = (r2).get();
        boolean ret3 = (r3).get();
        // 7.关闭服务
        ser.shutdownNow();
    }
}

callable 的好处

  1. 可以定义返回值
  2. 可以抛出异常

案例

模拟龟兔赛跑

public class Race implements Runnable{
    private static String winner;

    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            // 兔子休息
            if (Thread.currentThread().getName().equals("兔子") && i % 10 == 0) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if (gameOver(i)) {
                break;
            }
            System.out.println(Thread.currentThread().getName() + "-->跑了 " + i + " 步");
        }
    }

    private boolean gameOver(int steps) {
        if (winner != null) {
            return true;
        } else if (steps >= 100){
            winner = Thread.currentThread().getName();
            System.out.println("winner is " + winner);
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args) {
        Race race = new Race();
        new Thread(race, "兔子").start();
        new Thread(race, "乌龟").start();
    }
}

// output
......
乌龟-->跑了99步
winner is 乌龟

静态代理模式

  1. 真实对象和代理对象都要实现同一个接口
  2. 代理对象要代理真实角色
  3. 好处:代理对象可以做很多真实对象做不了的事情
    真实对象专注做自己的事情
public class StaticProxy {
    public static void main(String[] args) {
        WeddingCompany weddingCompany = new WeddingCompany(new You());
        weddingCompany.HappyMarry();
    }
}

interface Marry {
    void HappyMarry();
}

// 真实角色
class You implements Marry {
    @Override
    public void HappyMarry() {
        System.out.println("marry");
    }
}

// 代理角色
class WeddingCompany implements Marry {
    private Marry marryTarget;
    public WeddingCompany (Marry marryTarget) {
        this.marryTarget = marryTarget;
    }
    @Override
    public void HappyMarry() {
        marryBefore();
        this.marryTarget.HappyMarry();
        marryAfter();
    }

    private void marryBefore() {
        System.out.println("Layout site~");
    }

    private void marryAfter() {
        System.out.println("Clean environment~");
    }
}

动态代理模式

Lambda表达式

函数式接口

任何接口,如果只包含唯一一个抽象方法,那么它就是一个函数式接口

public interface Runnable {
    public abstract void run();
}

对于函数式接口,我们就可以通过lambda表达式来创建该接口的对象

无参lambda表达式
public class TestLambda {
    // 3.静态内部类
    static class Like2 implements ILike {
        @Override
        public void lambda() {
            System.out.println("I like lambda2");
        }
    }

    public static void main(String[] args) {
        ILike like = new Like();
        like.lambda();

        like = new Like2();
        like.lambda();

        // 4.局部内部类
        class Like3 implements ILike {
            @Override
            public void lambda() {
                System.out.println("I like lambda3");
            }
        }
        like = new Like3();
        like.lambda();

        // 5.匿名内部类, 没有类的名称,必须借助接口或者父类
        like = new ILike() {
            @Override
            public void lambda() {
                System.out.println("I like lambda4");
            }
        };
        like.lambda();

        // 6.用lambda简化
        like = ()->{
            System.out.println("I like lambda5");
        };
        like.lambda();
    }
}

// 1.定义一个接口
interface ILike {
    void lambda();
}

// 2.实现类
class Like implements ILike {
    @Override
    public void lambda() {
        System.out.println("I like lambda");
    }
}
带参lambda表达式
public class TestLambda2 {
    public static void main(String[] args) {
        // 1.lambda表达式
        ILove love = (int sth)-> {
            System.out.println("I love you -->" + sth);
        };
        love.love(1);
        // 2.简化参数类型
        love = (sth)-> {
            System.out.println("I love you -->" + sth);
        };
        love.love(2);
        // 3.简化括号
        love = sth-> {
            System.out.println("I love you -->" + sth);
        };
        love.love(3);
        // 4.简化大括号(代码只有1行)
        love = sth-> System.out.println("I love you -->" + sth);
        love.love(4);
    }
}

interface ILove {
    void love(int sth);
}

线程停止

  1. 建议线程正常停止,利用次数,不建议死循环
  2. 建议使用标志位,设置一个标志位
  3. 不要使用stop()或者destroy()等JDK不建议使用的方法
public class TestStop implements Runnable{
    // 1.设置一个标志位
    private boolean flag = true;
    @Override
    public void run() {
        int i = 0;
        while (flag) {
            System.out.println("run ... thread " + i++);
        }
    }

    // 2.设置一个公开的方法停止线程,转换标志位
    public void stop() {
        this.flag = false;
    }

    public static void main(String[] args) {
        TestStop testStop  = new TestStop();
        new Thread(testStop).start();
        for (int i = 0; i < 1000; i++) {
            System.out.println("main " + i);
            if (i == 900) {
                testStop.stop();
                System.out.println("该线程停止了");
            }
        }
    }
}

线程休眠

  1. sleep时间达到后,线程进入就绪状态
  2. sleep可以模拟网络延时、倒计时等
    模拟网络延时:放大问题的发生性
  3. 每一个对象都有一个锁,sleep不会释放锁

线程礼让

yield

  1. 礼让线程,让当前正在执行的线程暂停,但不阻塞
  2. 讲线程从运行态转为就绪态
  3. 让cpu重新调度,礼让不一定成功,看cpu心情
public class TestYield {
    public static void main(String[] args) {
        MyYield myYield = new MyYield();

        new Thread(myYield, "a").start();
        new Thread(myYield, "b").start();
    }
}

class MyYield implements Runnable {

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "线程开始执行");
        Thread.yield(); // 线程礼让
        System.out.println(Thread.currentThread().getName() + "线程停止执行");
    }
}

join插队

  1. join合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞
public class TestJoin implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("线程vip来了" + i);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        // 启动我们的线程
        TestJoin testJoin = new TestJoin();
        Thread thread = new Thread(testJoin);
        thread.start();

        // 主线程
        for (int i = 0; i < 100; i++) {
            if (i == 20) {
                thread.join();
            }
            System.out.println("main " + i);
        }
    }
}

线程状态测试

public class TestState {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(()->{
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        // 观察状态
        Thread.State state = thread.getState();
        System.out.println(state);  // new

        // 观察启动后
        thread.start(); // 启动线程
        state = thread.getState();
        System.out.println(state);  // run

        while (state != Thread.State.TERMINATED) { // 只要线程不终止,就一直输出状态
            Thread.sleep(1000);
            state = thread.getState();  // 更新线程状态
            System.out.println(state);  // 输出状态
        }
    }
}

线程优先级

  1. 调度优先级用数字表示,范围1-10,数字越大优先级越高
public class TestPriority {
    public static void main(String[] args) {
        // 主线程默认优先级
        System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());

        MyPriority myPriority = new MyPriority();
        Thread t1 = new Thread(myPriority);
        Thread t2 = new Thread(myPriority);
        Thread t3 = new Thread(myPriority);
        Thread t4 = new Thread(myPriority);
        Thread t5 = new Thread(myPriority);
        Thread t6 = new Thread(myPriority);

        // 先设置优先级,再启动
        t1.start();

        t2.setPriority(1);
        t2.start();

        t3.setPriority(4);
        t3.start();

        t4.setPriority(Thread.MAX_PRIORITY);
        t4.start();

        t5.setPriority(-1);
        t5.start();

        t6.setPriority(11);
        t6.start();
    }
}

class MyPriority implements Runnable {

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());
    }
}

// output
main-->5
Thread-0-->5
Thread-3-->10
Thread-2-->4
Thread-1-->1
Exception in thread "main" java.lang.IllegalArgumentException
	at java.base/java.lang.Thread.setPriority(Thread.java:1137)
	at thread.TestPriority.main(TestPriority.java:33)

优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用了

守护线程daemon

  1. 线程分为用户线程守护线程
  2. 虚拟机必须确保用户线程执行完毕
  3. 虚拟机不用等待守护线程执行完毕
  4. 守护进程:如后台记录操作日志、监控内存、垃圾回收等
// 上帝守护你
public class TestDaemon {
    public static void main(String[] args) {
        God god = new God();
        You you = new You();

        Thread thread = new Thread(god);
        thread.setDaemon(true); // 默认false,表示用户线程,正常的线程都是用户线程

        thread.start(); // 上帝守护线程启动
        
        new Thread(you).start();
    }
}

// 上帝
class God implements Runnable {

    @Override
    public void run() {
        while (true) {
            System.out.println("上帝保佑着你");
        }
    }
}

// 你
class You implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 36500; i++) {
            System.out.println("你一生都挺开心的");
        }
        System.out.println("========goodbye world!========");
    }
}

线程不安全案例

多个线程操作同一个资源的情况下, 线程不安全

1、买票

// 多个线程操作同一个资源的情况下, 线程不安全
public class UnsafeBuyTicket implements Runnable{
    private int ticketNum = 10;
    boolean flag = true;
    public void run() {
        while (flag) {
            buy();
        }
    }

    // synchronize方法,锁的是this
    private void buy() {
        while (flag) {
            if (ticketNum <= 0) {
                flag = false;
                return;
            }
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "-->拿到了第" + ticketNum-- +"票");
        }
    }

    public static void main(String[] args) {
        UnsafeBuyTicket t1 = new UnsafeBuyTicket();

        new Thread(t1, "player1").start();
        new Thread(t1, "player2").start();
        new Thread(t1, "player3").start();
    }
}


// output
player2-->拿到了第10票
player1-->拿到了第9票
player3-->拿到了第8票
player2-->拿到了第7票
player1-->拿到了第6票
player3-->拿到了第5票
player3-->拿到了第4票
player1-->拿到了第3票
player2-->拿到了第2票
player1-->拿到了第0票
player3-->拿到了第1票
player2-->拿到了第1

2、取钱

public class UnsafeBank {
    public static void main(String[] args) {
        Account account = new Account(100, "your_money");

        Drawing you = new Drawing(account,50,"you");
        Drawing wife = new Drawing(account,100,"wife");

        you.start();
        wife.start();
    }
}

// 账户
class Account {
    int money;
    String name;

    public Account(int money, String name) {
        this.money = money;
        this.name = name;
    }
}

// 银行
class Drawing extends Thread {
    Account account;    // 账户
    int drawingMoney;   // 取了多少钱
    int curMoney;       // 余额

    public Drawing(Account account, int drawingMoney, String name) {
        super(name);
        this.account = account;
        this.drawingMoney = drawingMoney;
    }

    @Override
    public void run() {
        if (account.money < drawingMoney) {
            System.out.println(Thread.currentThread().getName() + "钱不够,取不了");
            return;
        }

        // 延时,让两个线程都走到这,然后继续往下
        // sleep可以放大问题的发生性
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 更新余额
        account.money -= drawingMoney;
        curMoney += drawingMoney;

        System.out.println(account.name + "余额为: " + account.money);
        // this.getName() == Thread.currentThread().getName()
        System.out.println(this.getName() + "手里的钱为: " + curMoney);
    }
}

// output
your_money余额为: 0
wife手里的钱为: 100
your_money余额为: -50
you手里的钱为: 50

3、不安全的List

import java.util.ArrayList;
import java.util.List;

public class UnsafeList {
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < 10000; i++) {
            new Thread(()->{
                list.add(Thread.currentThread().getName());
            }).start();
        }
        
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        System.out.println(list.size());
    }
}

// output
9993(如果是1000,说明cpu性能太好了,可以把10000调大几个数量级,即可看到现象)

线程同步synchronize

  1. 一个线程持有锁,会导致其他所有需要此锁的线程挂起
  2. 多线程竞争下,加锁、释放锁会导致比较多的上下文切换和调度延时,引起性能问题
  3. 如果一个优先级高的线程等待一个优先级低的线程释放锁,会导致优先级倒置,引起性能问题

synchronize方法

  1. 给一个方法加上synchronize关键字,该方法就变成了synchronize方法
  2. synchronize方法控制对象的访问,每个对象对应一把锁,每个synchronize方法必须获得调用该方法的对象的所才能执行,否则线程会阻塞
  3. 方法一旦执行,就会独占该锁,直到该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行

缺陷

若将一个大的方法声明为synchronize方法,将会影响效率

修改上述第一个例子,买票

在buy方法前加上synchronize,即可达到预期效果

public class UnsafeBuyTicket implements Runnable{
    private int ticketNum = 10;
    boolean flag = true;
    public void run() {
        while (flag) {
            buy();
        }
    }

    // synchronize方法,锁的是this
    private synchronized void buy() {
        while (flag) {
            if (ticketNum <= 0) {
                flag = false;
                return;
            }
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "-->拿到了第" + ticketNum-- +"票");
        }
    }

    public static void main(String[] args) {
        UnsafeBuyTicket t1 = new UnsafeBuyTicket();

        new Thread(t1, "player1").start();
        new Thread(t1, "player2").start();
        new Thread(t1, "player3").start();
    }
}

synchronize块

  1. 由于代码中只有修改的地方才需要synchronize,所以我们可以不synchronize整个方法,而去synchronize块(即方法中的某部分{})
  2. 同步块 synchronize(Obj){}
  3. Obj称为同步监视器

关于同步监视器

  • Obj可以是任何对象,但是推荐使用共享资源作为同步监视器
  • 同步方法中,无需指定同步监视器,因为同步方法的同步监视器就是this,就是这个对象本身,或者是class

同步监视器的执行过程

  1. 第一个线程访问,锁定同步监视器,执行其中代码
  2. 第二个线程访问,发现同步监视器被锁定,无法访问
  3. 第一个线程访问完毕,解锁同步监视器
  4. 第二个线程访问完毕,发现同步监视器没有锁,然后锁定并访问

修改上述第2个例子,取钱

在run方法内,加一个synchronize块,把需要运行的方法(可能不安全的方法)放入块内

public class UnsafeBank {
    public static void main(String[] args) {
        Account account = new Account(100, "your_money");

        Drawing you = new Drawing(account,50,"you");
        Drawing wife = new Drawing(account,100,"wife");

        you.start();
        wife.start();
    }
}

// 账户
class Account {
    int money;
    String name;

    public Account(int money, String name) {
        this.money = money;
        this.name = name;
    }
}

// 银行
class Drawing extends Thread {
    Account account;    // 账户
    int drawingMoney;   // 取了多少钱
    int curMoney;       // 余额

    public Drawing(Account account, int drawingMoney, String name) {
        super(name);
        this.account = account;
        this.drawingMoney = drawingMoney;
    }

    @Override
    public void run() {
        synchronized (account) {
            if (account.money < drawingMoney) {
                System.out.println(Thread.currentThread().getName() + "钱不够,取不了");
                return;
            }

            // 延时,让两个线程都走到这,然后继续往下
            // sleep可以放大问题的发生性
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 更新余额
            account.money -= drawingMoney;
            curMoney += drawingMoney;

            System.out.println(account.name + "余额为: " + account.money);
            // this.getName() == Thread.currentThread().getName()
            System.out.println(this.getName() + "手里的钱为: " + curMoney);
        }
    }
}

补充JUC

import java.util.concurrent.CopyOnWriteArrayList;

// 测试JUC安全类型的集合
public class TestJUC {
    public static void main(String[] args) {
        CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
        for (int i = 0; i < 10000; i++) {
            new Thread(()->{
                list.add(Thread.currentThread().getName());
            }).start();
        }
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(list.size());
    }
}

死锁

  1. 若某一个synchronize同时拥有==“两个以上对象的锁”==时,就可能会发生死锁问题
public class DeadLock {
    public static void main(String[] args) {
        Makeup girl1 = new Makeup(0, "girl1");
        Makeup girl2 = new Makeup(0, "girl2");

        girl1.start();
        girl2.start();
    }
}

// 口红
class LipStick {
}

// 镜子
class Mirror {
}

class Makeup extends Thread {
    // static用来保证,需要用到的资源只有1份
    static LipStick lipStick = new LipStick();
    static Mirror mirror = new Mirror();

    int choice;
    String girName;

    public Makeup(int choice, String girName) {
        this.choice = choice;
        this.girName = girName;
    }

    @Override
    public void run() {
        // 化妆
        try {
            makeup();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void makeup() throws InterruptedException {
        if (choice == 0) {
            synchronized (lipStick) { // 获得口红的锁
                System.out.println(this.girName + "获得口红的锁");
                Thread.sleep(3000);
                synchronized (mirror) { // 3s后获得镜子的锁
                    System.out.println(this.girName + "获得镜子的锁");
                }
            }
        } else {
            synchronized (mirror) { // 获得镜子的锁
                System.out.println(this.girName + "获得镜子的锁");
                Thread.sleep(2000);
                synchronized (lipStick) { // 2s后获得口红的锁
                    System.out.println(this.girName + "获得口红的锁");
                }
            }
        }
    }
}

如果把上述例子的synchronize块并列放置,则不会发生死锁

Lock锁

  1. JDK5.0开始提供 Lock
  2. Lock 通过显示定义同步锁对象来实现同步,同步锁使用Lock对象充当
  3. 锁提供了对共享资源的独占访问,每次只能有一个线程对Lock对象加锁,线程开始访问共享资源之前应先获得Lock对象
  4. ReentrantLock(可重入锁)类实现了Lock,它拥有synchronize相同的并发性和内存语义,在实现线程安全的控制中,比较常用的是ReentrantLock,可以显示加锁、释放锁

用Lock锁修改上述第1个例子

import java.util.concurrent.locks.ReentrantLock;

public class TestLock {
    public static void main(String[] args) {
        TestLock2 testLock2 = new TestLock2();

        new Thread(testLock2).start();
        new Thread(testLock2).start();
        new Thread(testLock2).start();
    }
}

class TestLock2 implements Runnable {
    private int ticketNum = 10;
    boolean flag = true;

    // 定义lock锁
    private ReentrantLock lock = new ReentrantLock();

    public void run() {
        while (flag) {
            buy();
        }
    }

    private void buy() {
        while (flag) {
            try {
                lock.lock(); // 加锁
                if (ticketNum <= 0) {
                    flag = false;
                    return;
                }
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "-->拿到了第" + ticketNum-- +"票");
            } finally {
                // 解锁
                lock.unlock();
            }
        }
    }
}

synchronize与Lock对比

  1. Lock是显示锁(需要手动开启和关闭), 而synchronize是隐式锁,出了作用域自动释放
  2. Lock只有代码块锁,synchronize还可以锁方法
  3. 使用Lock,JVM将花费较少的时间来调度线程,性能更好,并且具有更好的扩展性(子类更多)
  4. 优先使用顺序: Lock > synchronize块(已经进入了方法体,分配了相应资源) > synchronize方法(在方法体外)

生产者消费者问题

管程法

// 测试生产者消费之模型-->利用缓冲区解决:管程法
public class TestPC {
    public static void main(String[] args) {
        SynContainer container = new SynContainer();

        new Producer(container).start();
        new Consumer(container).start();
    }
}

// 生产者
class Producer extends Thread {
    SynContainer container;

    public Producer(SynContainer container) {
        this.container = container;
    }

    // 生产方法
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            container.push(new Product(i));
            System.out.println("生产了-->" + i + "只鸡");
        }
    }
}

// 消费者
class Consumer extends Thread {
    SynContainer container;

    public Consumer(SynContainer container) {
        this.container = container;
    }

    // 消费方法
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("消费了-->" + container.pop().id + "只鸡");
        }
    }
}

// 产品
class Product extends Thread {
    int id;

    public Product(int id) {
        this.id = id;
    }
}

// 缓冲区
class SynContainer {

    // 产品数组缓冲区
    Product[] products = new Product[10];
    int count = 0;

    // 生产者放入产品
    public synchronized void push(Product product) {
        if (count >= products.length) { // 如果缓冲区满,则等待消费者消费
            // 通知消费者等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // 如果缓冲区不满,则将产品放入缓冲区
        products[count++] = product;

        // 通知消费者消费
        this.notifyAll();

    }

    // 消费者消费产品
    public synchronized Product pop(){
        // 判断能否消费
        if (count <= 0) { // 如果缓冲区为空,则等待生产者生产
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // 如果缓冲区不空,则消费者消费
        Product product = products[--count];
        // 通知生产者生产
        this.notifyAll();

        return product;
    }
}

信号灯法(缓冲区为1)

// 测试生产者消费者问题2: 信号灯法
public class TestPC2 {
    public static void main(String[] args) {
        TV tv = new TV();
        new Player(tv).start();
        new Watcher(tv).start();
    }
}

// 生产者-->演员
class Player extends Thread {
    TV tv;
    public Player(TV tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            if (i % 2 == 0) {
                this.tv.play("节目播放中");
            } else {
                this.tv.play("广告时间");
            }
        }
    }
}

// 消费者-->观众
class Watcher extends Thread {
    TV tv;
    public Watcher(TV tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            tv.watch();
        }
    }
}

// 产品-->节目
class TV {
    // 演员表演,观众等待 T
    // 观众观看,演员等待 F
    String voice; // 表演的节目
    boolean flag = true;

    // 表演
    public synchronized void play(String voice) {
        if (!flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("演员表演了:" + voice);
        // 通知观众观看
        this.notifyAll();
        this.voice = voice;
        this.flag = !this.flag;
    }

    // 观看
    public synchronized void watch() {
        if (flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("观众观看了:" + voice);
        // 通知演员表演
        this.notifyAll();
        this.flag = !this.flag;
    }
}

线程池

背景

由于经常需要创建、销毁、使用特别大的资源,比如并发情况下的线程,对性能影响很大

思路

可以提前创建好多个线程,放入线程池中,使用时直接获取,使用完后放回池中,可以避免频繁创建销毁、实现重复利用,类似生活中的公共交通工具

优点

  1. 提高响应速度(较少了创建线程需要的时间)
  2. 降低资源消耗(重复利用线程池中的线程,不需要每次都创建)
  3. 便与线程管理(核心池的大小、最大线程数、线程没有任务时最长保持多长时间后会终止)
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

// 测试线程池
public class TestPool {
    public static void main(String[] args) {
        // 1.创建服务,创建线程池
        ExecutorService service = Executors.newFixedThreadPool(10);

        // 执行
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());

        // 2.关闭连接
        service.shutdownNow();
    }
}

class MyThread implements Runnable {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

万独孤

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值