【Java多线程】轻松搞定Java多线程(二)

Java 多线程详解(二)

1、线程状态

1.1 线程状态

1

1.2 线程方法

方法说明
setPriority(int newPriority)更改线程的优先级
static void sleep(long millis)在指定的毫秒级内让当前正在执行的线程休眠
void join()等待该线程终止
static void yield()暂停当前正在执行的线程对象,并执行其他线程
void interrupt()中断线程(不建议使用)
boolean isAlive()测试线程是否处于活动状态
停止线程
  • 不推荐使用JDK提供的stop()、destroy()方法。(已废弃)
  • 推荐线程自己停下来
  • 建议使用一个标志位进行终止变量,当flag=false,则终止线程运行
/**
 * 测试stop
 * 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) {
                /**
                 * 调用stop()方法,切换标志位,让线程停止
                 */
                testStop.stop();
                System.out.println("线程停止了");
            }
        }
    }
}
线程休眠
  • sleep(时间)指定当前线程阻塞的毫秒数;
  • sleep存在异常InterruptedException;
  • sleep时间达到后线程进入就绪状态;
  • sleep可以模拟网络延时,倒计时等;
  • 每一个对象都有一个锁,sleep不会释放锁。
模拟网络延时
/**
 * 模拟网络延时:放大问题的发生性
 */
public class TestSleep implements Runnable {
    /**
     * 票数
     */
    private int ticketsNums = 20;

    @Override
    public void run() {
        while (true) {
            if (ticketsNums <= 0) {
                break;
            }

            /**
             * 模拟延时
             */
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "拿到了" + ticketsNums-- + "票");
        }
    }

    public static void main(String[] args) {
        TestSleep ticket = new TestSleep();

        new Thread(ticket, "小明").start();
        new Thread(ticket, "老师").start();
        new Thread(ticket, "黄牛").start();
    }
}
模拟倒计时
/**
 * 模拟倒计时
 */
public class TestSleep2 {

    public static void main(String[] args) {
        try {
            tenDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void tenDown() throws InterruptedException {
        int num = 10;

        while (true) {
            Thread.sleep(1000);
            System.out.println(num--);
            if (num <= 0) {
                break;
            }
        }
    }
}
线程礼让
  • 礼让线程,让当前正在执行的线程暂停,但不阻塞
  • 将线程从运行状态转为就绪状态
  • 让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
  • Join合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞
  • 可以想象成插队
/**
 * 测试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 {
        /**
         * vip线程
         */
        TestJoin testJoin = new TestJoin();
        Thread thread = new Thread(testJoin);
        thread.start();

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

1.3 线程状态观测

image-20200908200728290

/**
 * 观察测试线程的状态
 */
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();
                }
            }
            System.out.println("///");
        });

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

        /**
         * 启动线程
         */
        thread.start();
        state = thread.getState();
        System.out.println(state);

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

}

1.4 线程优先级

/**
 * 测试线程优先级
 */
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);

        /**
         * 先设置优先级,再启动
         */
        t2.setPriority(1);
        t3.setPriority(4);
        t4.setPriority(Thread.MAX_PRIORITY);

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

}

class MyPriority implements Runnable {

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

1.5 守护线程

  • 线程分为用户线程守护线程
  • 虚拟机必须确保用户线程执行完毕
  • 虚拟机不用等待守护线程执行完毕
  • 如:后台记录操作日志,监控内存,垃圾回收等等…
/**
 * 测试守护线程
 * 上帝守护
 */
public class TestDaemon {

    public static void main(String[] args) {
        God god = new God();
        Human human = new Human();

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

        thread.start();

        /**
         * 用户线程启动
         */
        new Thread(human).start();
    }
}

/**
 * 上帝
 */
class God implements Runnable {

    @Override
    public void run() {
        while (true) {
            System.out.println("上帝守护");
        }
    }
}


/**
 * 人
 */
class Human implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 36500; i++) {
            System.out.println("活着");
        }
        System.out.println("======离开======");
    }
}

2、线程同步

多个线程操作同一个资源

2.1 并发

  • 并发:同一个对象多个线程同时操作

2.2 线程同步

  • 处理多线程问题时,多个线程访问同一个人对象(并发问题),并且某些线程还想修改这个对象。这个时候我们就需要线程同步。
  • 线程同步其实就是一种等待机制,多个需要同时访问此对象的线程进入这个对象的等待池形成队列,等待前面线程使用完毕,下一个线程再使用。
  • 形成条件:队列和锁
  • 由于同一进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突问题,为了保证数据在方法中被访问的正确性,在访问时加入锁机制(synchronized),当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放锁即可。存在以下问题:
    • 一个线程持有锁会导致其他所有需要此锁的线程挂起
    • 在多线程竞争下,加锁,释放锁会导致比较多的上下文切换和调度延时,引起性能问题
    • 如果一个优先级高的线程等待一个优先级低的线程释放锁,会导致优先级倒置,引起性能问题
不安全的买票
/**
 * 不安全的买票
 */
public class UnsafeBuyTicket {

    public static void main(String[] args) {
        BuyTicket station = new BuyTicket();

        new Thread(station, "小明").start();
        new Thread(station, "小红").start();
        new Thread(station, "小黑").start();

    }

}

class BuyTicket implements Runnable {

    /**
     * 票
     */
    private int ticketNums = 10;

    /**
     * 外部停止方式
     */
    boolean flag = true;

    @Override
    public void run() {
        /**
         * 买票
         */
        while (flag) {
            buy();
        }

    }

    private void buy() {
        /**
         * 判断是否有票
         */
        if (ticketNums <= 0) {
            flag = false;
            return;
        }

        /**
         * 模拟延迟
         */
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(Thread.currentThread().getName() + "拿到" + ticketNums--);
    }
}
不安全的取钱
/**
 * 不安全的取钱
 * 两个人用同一账号去银行取钱
 */
public class UnsafeBank {

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

        Drawing Jack = new Drawing(account, 50, "Jack");
        Drawing Rose = new Drawing(account, 100, "Rose");

        Jack.start();
        Rose.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 nowMoney;

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

    /**
     * 取钱
     */
    @Override
    public void run() {
        /**
         * 判断有没有钱
         */
        if (account.money - drawingMoney < 0) {
            System.out.println(Thread.currentThread().getName() + "余额不足");
            return;
        }

        /**
         * 模拟延时
         */
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        /**
         * 卡内余额
         */
        account.money = account.money - drawingMoney;

        /**
         * 手里的钱
         */
        nowMoney = nowMoney + drawingMoney;

        System.out.println(account.name + "余额为:" + account.money);
        System.out.println(this.getName() + "手里的钱:" + nowMoney);

    }
}
线程不安全的集合
/**
 * 线程不安全的集合
 */
public class UnsafeList {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            new Thread(() -> {
                list.add(Thread.currentThread().getName());
            }).start();
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(list.size());
    }
}
同步方法
  • 由于我们可以通过private关键字来保证数据对象只能被方法访问,所以我们只需要针对方法提出一套机制,这套机制就是synchronized关键字,它包括两种用法:
    • synchronized方法
    • synchronized块
    /**
     * 同步方法
     */
    public synchronized void method(int args) {}
  • synchronized方法控制对“对象”的访问,每一个对象对应一把锁,每个synchronized方法都必须获得调用该方法的对象的锁才能执行,否则线程会阻塞,方法一旦执行,就独占该锁,直到该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行

同步方法的弊端:

  • 方法里面需要修改的内容才需要锁,锁得太多,浪费资源
  • 若将一个大的方法声明为synchronized将会影响效率
安全的买票
/**
 * 安全的买票
 */
public class SafeBuyTicket {

    public static void main(String[] args) {
        BuyTicket station = new BuyTicket();

        new Thread(station, "小明").start();
        new Thread(station, "小红").start();
        new Thread(station, "小黑").start();
    }

}

class BuyTicket implements Runnable {

    /**
     * 票
     */
    private int ticketNums = 10;

    /**
     * 外部停止方式
     */
    boolean flag = true;

    @Override
    public void run() {
        /**
         * 买票
         */
        while (flag) {
            /**
             * 模拟延迟
             */
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            buy();
        }

    }

    /**
     * synchronized 同步方法,锁的是this
     */
    private synchronized void buy() {
        /**
         * 判断是否有票
         */
        if (ticketNums <= 0) {
            flag = false;
            return;
        }

        /**
         * 模拟延迟
         */
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(Thread.currentThread().getName() + "拿到" + ticketNums--);
    }
}
同步块
  • 同步块:synchronized(Obj) {}
  • Obj称之为同步监视器
    • Obj可以是任何对象,但是推荐使用共享资源作为同步监视器
    • 同步方法中无需指定同步监视器,因为同步方法的同步监视器就是this,就是这个对象本身,或者是class
  • 同步监视器的执行过程
    1. 第一个线程访问,锁定同步监视器,执行其中代码
    2. 第二个线程访问,发现同步监视器被锁定,无法访问
    3. 第一个线程访问完毕,解锁同步监视器
    4. 第二个线程访问,发现同步监视器没有锁,然后锁定访问
安全的取钱
/**
 * 安全的取钱
 * 两个人用同一账号去银行取钱
 */
public class SafeBank {

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

        Drawing Jack = new Drawing(account, 50, "Jack");
        Drawing Rose = new Drawing(account, 100, "Rose");

        Jack.start();
        Rose.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 nowMoney;

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

    /**
     * 取钱
     * synchronized默认锁this
     */
    @Override
    public void run() {

        /**
         * 同步块
         * 锁的对象就是变化的量,需要增删改的对象
         */
        synchronized (account) {
            /**
             * 判断有没有钱
             */
            if (account.money - drawingMoney < 0) {
                System.out.println(Thread.currentThread().getName() + "余额不足");
                return;
            }

            /**
             * 模拟延时
             */
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            /**
             * 卡内余额
             */
            account.money = account.money - drawingMoney;

            /**
             * 手里的钱
             */
            nowMoney = nowMoney + drawingMoney;

            System.out.println(account.name + "余额为:" + account.money);
            System.out.println(this.getName() + "手里的钱:" + nowMoney);
        }
    }
}
线程安全的集合
/**
 * 线程安全的集合
 */
public class SafeList {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            new Thread(() -> {
                /**
                 * 同步块
                 */
                synchronized (list) {
                    list.add(Thread.currentThread().getName());
                }
            }).start();
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(list.size());
    }
}
JUC安全类型的集合
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 测试JUC安全类型的集合
 */
public class TestJUC {

    public static void main(String[] args) {
        CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
        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());
    }
}

2.3 死锁

  • 多个线程各自占有一些共享资源,并且互相等待其他线程占有的资源才能运行,而导致两个或者多个线程都在等待对方释放资源,都停止执行的情形。某一个同步块同时拥有“两个以上对象的锁”时,就可能会发生“死锁”的问题。
/**
 * 死锁:多个线程互相抱着对方需要的资源,然后形成僵持
 */
public class DeadLock {

    public static void main(String[] args) {
        Makeup g1 = new Makeup(0, "一号");
        Makeup g2 = new Makeup(1, "二号");

        g1.start();
        g2.start();
    }

}

/**
 * 口红
 */
class Lipstick {}

/**
 * 镜子
 */
class Mirror {}

class Makeup extends Thread {

    /**
     * 需要的资源只有一份,用static来保证只有一份
     */
    static Lipstick lipstick = new Lipstick();
    static Mirror mirror = new Mirror();

    int choice; // 选择
    String name; // 使用化妆品的人

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

    @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.name + "获得口红的锁");
                Thread.sleep(1000);

                /**
                 * 一秒钟后想获得镜子
                 */
                synchronized (mirror) {
                    System.out.println(this.name + "获得镜子的锁");
                }
            }
        } else {
            /**
             * 获得镜子的锁
             */
            synchronized (mirror) {
                System.out.println(this.name + "获得镜子的锁");
                Thread.sleep(2000);

                /**
                 * 两秒钟后想获得口红
                 */
                synchronized (lipstick) {
                    System.out.println(this.name + "获得口红的锁");
                }
            }
        }
    }
}
死锁避免方法
  • 产生死锁的四个必要条件:
    1. 互斥条件:一个资源每次只能被一个进程使用。
    2. 请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放。
    3. 不剥夺条件:进程已获得的资源,在未使用完之前,不能强行剥夺。
    4. 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系。

2.4 锁

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

/**
 * 测试Lock锁
 */
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 {

    int ticketNums = 10;

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

    @Override
    public void run() {
        while (true) {
            lock.lock();
            try {
                if (ticketNums > 0) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(ticketNums--);
                } else {
                    break;
                }
            } finally {
                lock.unlock();
            }
        }
    }
}
synchronized与Lock的对比
  • Lock是显式锁(手动开启和关闭锁),synchronized是隐式锁,出了作用域自动释放。
  • Lock只有代码块锁,synchronized有代码块锁和方法锁。
  • 使用Lock锁,JVM将花费较少的时间来调度线程,性能更好。并且具有更好的扩展性(提供更多的子类)。
  • 优先使用顺序:
    • Lock > 同步代码块(已经进入了方法体,分配了相应的资源) > 同步方法(在方法体之外)

3、线程协作

3.1 生产者消费者问题

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

这是一个线程同步问题,生产者和消费者共享同一个资源,并且生产者和消费者之间相互依赖,互为条件。

在生产者消费者问题中,仅有synchronized是不够的

  • synchronized可阻止并发更新同一个共享资源,实现了同步
  • synchronized不能用来实现不同线程之间的消息传递(通信)

3.2 线程通信

  • Java提供了几个方法解决线程之间的通信问题
方法名作用
wait()表示线程一直等待,直到其他线程通知,与sleep不同,会释放锁
wait(long timeout)指定等待的毫秒数
notify()唤醒一个处于等待状态的线程
notifyAll()唤醒同一个对象上所有调用wait()方法的线程,优先级高的线程优先调度

注意:

均是Object类的方法,都只能在同步方法或者同步代码块中使用,否则会抛出异常IllegalMonitorStateException

3.3 管理法

/**
 * 测试:生产者消费者模型-->利用缓冲区解决:管理法
 */
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++) {
            System.out.println("生产了第" + i + "只鸡");
            container.push(new Chicken(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("消费了第" + i + "只鸡");
            container.pop();
        }
    }
}

/**
 * 产品
 */
class Chicken {
    /**
     * 产品编号
     */
    int id;

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

/**
 * 缓冲区
 */
class SynContainer {
    /**
     * 需要一个容器大小
     */
    Chicken[] chickens = new Chicken[10];

    /**
     * 容器计数器
     */
    int count = 0;

    /**
     * 生产者生产产品
     */
    public synchronized void push(Chicken chicken) {
        /**
         * 如果容器满了,就需要等待消费者消费
         */
        if (count == chickens.length) {
            /**
             * 通知消费者消费,生产等待
             */
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        /**
         * 如果没有满,就放入产品
         */
        chickens[count] = chicken;
        count++;

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

    /**
     * 消费者消费产品
     */
    public synchronized Chicken pop() {
        /**
         * 判断能否消费
         */
        if (count == 0) {
            /**
             * 等待生产者生产,消费者等待
             */
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        /**
         * 如果可以消费
         */
        count--;
        Chicken chicken = chickens[count];

        /**
         * 消费完通知生产者生产
         */
        this.notifyAll();
        return chicken;
    }
}

3.4 信号灯法

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

}

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

    @Override
    public void run() {
        for (int i = 0; i < 200; i++) {
            if (i%2 == 0) {
                this.film.play("盗梦空间");
            } else {
                this.film.play("星际穿越");
            }
        }
    }
}

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

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

/**
 * 产品-->电影
 */
class Film {
    /**
     * 演员演戏,观众等待    T
     * 观众观看,演员等待    F
     */

    /**
     * 表演的电影
     */
    String name;
    boolean flag = true;

    public synchronized void play(String name) {

        if (!flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("演员表演了:"+name);
        /**
         * 通知观众观看
         */
        this.notifyAll();
        this.name = name;
        this.flag = !this.flag;
    }

    /**
     * 观众观看
     */
    public synchronized void watch() {
        if(flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("观看了:"+name);

        /**
         * 通知演员演戏
         */
        this.notifyAll();
        this.flag = !this.flag;
    }
}

4、线程池

  • 背景:经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大。
  • 思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完返回池中。可以避免频繁创建销毁、实现重复利用。类似生活中的公共交通工具。
  • 好处:
    • 提高响应速度(减少了创建新线程的时间)
    • 降低资源消耗(重复利用线程池中线程,不需要每次都创建)
    • 便于线程管理
      • corePoolSixe:核心池的大小
      • maximumPoolSize:最大线程数
      • keepAliveTime:线程没有任务时最多保持多长时间后会终止
使用线程池
  • JDK5.0起提供了线程池相关API:ExecutorService和Executors
  • ExecutorService:真正的线程池接口。常见子类ThreadPoolExecutor
    • void execute(Runnable command):执行任务/命令,没有返回值,一般用来执行Runnable
    • < T >Future< T > submit(Callable< T > task):执行任务,有返回值,一般用来执行Callable
    • void shutdown():关闭线程池
  • Executors:工具类、线程类的工厂类,用于创建并返回不同类型的线程池
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

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

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

        /**
         * 2.关闭服务
         */
        service.shutdown();

    }
}

class MyThread implements Runnable {

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值