多线程

197 阅读11分钟

多线程的介绍

image.png

image.png

线程创建

继承Thread类

注意:线程开始不一定立即执行,由CPU调度。

image.png

package dom01;


// 创建线程的方式一:继承Thread,重写run()方法,调用start开始线程。
public class TestThread extends Thread {
    @Override
    public void run() {
        // run方法线程体
        for (int i = 0; i < 20; i++) {
            System.out.println("我在看代码===>"+i);
        }
    }
    // main方法,主线程
    public static void main(String[] args) {

        //创建一个线程对象
        TestThread testThread = new TestThread();
        //调用start方法开启线程
        testThread.start();// 交替执行 ,每次结果都不同(指顺序)

        for (int i = 0; i < 20; i++) {
            System.out.println("我在学习多线程===>"+i);
        }
    }
}

输出结果如下

image.png

实现Runnable接口

image.png

package dom01;
//  创建线程的方法二: 实现runnable接口,重写run方法,执行线程需要丢入runnable接口实现类,调用start方法。
public class TestThread2 implements Runnable{
    @Override
    public void run() {
        // run方法线程体
        for (int i = 0; i < 20; i++) {
            System.out.println("我在看代码===>"+i);
        }
    }
    public static void main(String[] args) {
        // 创建一个runnable接口的实现类对象
        TestThread2 testThread2 = new TestThread2();

        // 创建线程对象,通过线程对象来开启我们的线路,代理
        new Thread(testThread2).start();
        for (int i = 0; i < 20; i++) {
            System.out.println("我在学习多线程===>"+i);
        }
    }
}

并发问题

package dom01;

// 多个线程同时操作同一个对象
public class TestThread4 implements Runnable{

     private int ticketNums = 10;

    @Override
    public void run() {
        while (true){
            if (ticketNums<=0){
                break;
            }
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName()+ "拿到了第" +ticketNums--+ "张票");
        }
    }

    public static void main(String[] args) {
        TestThread4 ticket = new TestThread4();
 
        new Thread(ticket,"小明").start();
        new Thread(ticket,"老师").start();
        new Thread(ticket,"黄牛").start();
    }
}

image.png

静态代理模式

代理对象做真实对象做不了的东西,真实对象专心做自己的东西

package dom01;

public class StacticProxy {
    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("秦老师要结婚了");
        }
    }

    //代理角色
    class WeddingCompany implements Marry{
        private Marry target;

        public WeddingCompany(Marry target) {
            this.target = target;
        }

        @Override
        public void HappyMarry() {
            before();
            this.target.HappyMarry();
            after();
        }

        private void before() {
            System.out.println("结婚之前布置现场");
        }

        private void after() {
            System.out.println("收尾款");
            
        }

    }

Lamda表达式

意义

  1. 用于简化代码。
  2. 避免内部类定义过多。
  3. 可以让代码更简洁
  4. 丢掉无意义代码,只留下核心逻辑。
package dom01;

public class lamda {
    // 3.静态内部类
    static class Lick2 implements ILike{
        @Override
        public void Iambda() {
            System.out.println("i like lanbda2");
        }
    }
    public static void main(String[] args) {
        ILike lick = new Lick();
        lick.Iambda();

        lick = new Lick2();
        lick.Iambda();

        // 4.局部内部类
        class Lick3 implements ILike{
            @Override
            public void Iambda() {
                System.out.println("i like lanbda2");
            }
        }
        lick = new Lick3();
        lick.Iambda();

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

        // 6.用Iamda简化
        lick = ()-> {
            System.out.println("I lick lanbda5");
        };
        lick.Iambda();
    }
}
//  1.定义一个函数式接口(指只有一个抽象方法)
interface ILike{
    void Iambda();
}
// 2.实现类
class Lick implements ILike{
    @Override
    public void Iambda() {
        System.out.println("i like lanbda1");
    }
}
package dom01;

public class TextIlove {

    public static void main(String[] args) {
        // 1.Lambda表示简化
        Ilove love = (int a)->{
            System.out.println("输出"+a);
        };
        love.love(1);

        // 2.简化参数类型
        Ilove love = (a)->{
            System.out.println("输出"+a);
        };
        love.love(2);

        // 3.简化括号
        Ilove love = a->{
            System.out.println("输出"+a);
        };
        love.love(3);

        // 4.简化花括号
        Ilove love = a-> System.out.println("输出"+a);;
        love.love(4);
        /*
        注意
        1.省略花括号是因为只有一行代码
        2.必须接口是函数式接口(只有一个方法)
        3.多个参数也可以去掉参数类型,但要加括号
         */
    }
}

interface Ilove{
    void love(int a);
}

线程状态

image.png

image.png

线程停止

package dom02;

// 测试stop
// 建议线程正常停止
// 建议使用标志位
// 不要使用stop或destroy等过时或者JDK不建议使用的方法
public class textstop implements Runnable{
    // 1.设置一个标识符
    private boolean flag = true;

    @Override
    public void run() {
        while (flag){
            System.out.println("run...Thread...");
        }
    }

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

    public static void main(String[] args) {
        textstop textstop = new textstop();
        new Thread(textstop).start();

        for (int i = 0; i < 1000; i++) {
            System.out.println("main"+i);
            if (i==900){
                // 调用stop方法切换标志位,让线程停止
                textstop.stop();
                System.out.println("线程停止了");
            }
        }
    }
}

线程休眠-sleep

4d3ee75d10a50c45de253b8410dbefc.jpg

package dom01;
// 模拟倒计时
public class TestSleep2 {
    public static void main(String[] args) {
        try {
            tenDown();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public static void tenDown() throws InterruptedException {
        int num = 10;
        while (true){
            Thread.sleep(1000);
            System.out.println(num--);
            if (num==0){
                break;
            }
        }
    }
}

线程礼让

de3e5508d2e68bd496249e6f23c44bf.jpg

package dom01;
// 测试礼让线程
// 礼让不一定成功
public class TestYeld {
    public static void main(String[] args) {
        MyYield myYield = new MyYield();

        new Thread(myYield,"b").start();
        new Thread(myYield,"a").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合并线程,代词线程执行完毕后,再执行其他线程,其他线程阻塞

package dom01;

// 测试Join方法
// 理解为插队
public class TestJoin implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 80; i++) {
            System.out.println("线程vip来了"+i);
        }
    }

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

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

线程状态观测

3edbf30d768a5027b03f016bfdbde1c.jpg

package dom01;

public class TsteState {
    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) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println("/////");
        });


        // 观察状态
        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(100);
            state = thread.getState(); //更新线程状态
            System.out.println(state); // 输出状态
        }
    }
}

线程的优先级

853fb07f21538aa37b9b58b2a4b8ccb.jpg

package dom01;

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

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

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

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

        t4.setPriority(Thread.MAX_PRIORITY); // MAX_PRIORITY == 10
        t4.start();
    }
}

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

守护线程

363008aac7c078c32dcc2aaff64740f.jpg

package dom01;

// 测试守护线程
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("-==== goodbay!world!====");
    }
}

线程同步

线程同步机制

f8ea655c31a68eb0a44e0eb07cc8939.jpg

package syn;

// 不安全买票
// 线程不安全,存在负数
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();

        new Thread(buyTicket,"苦逼的我").start();
        new Thread(buyTicket,"牛逼的你们").start();
        new Thread(buyTicket,"可恶的黄牛党").start();

    }
}

class BuyTicket implements Runnable{
    // 票
    private int ticketNums = 10;
    boolean flat = true; // 外部停止方式
    @Override
    public void run() {
        // 买票
        while (flat){
            try {
                buy();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
    private void buy() throws InterruptedException {
        // 判断是否有票
        if (ticketNums<=0){
            flat = false;
            return;
        }
        // 模拟延时
        Thread.sleep(100);

        // 买票
        System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
    }
}

出现负数,线程不安全

image.png

同步方法

c41eb9f6158d9acfefff25c57d01b0e.jpg

package syn;

// 不安全买票
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();

        new Thread(buyTicket,"苦逼的我").start();
        new Thread(buyTicket,"牛逼的你们").start();
        new Thread(buyTicket,"可恶的黄牛党").start();

    }
}

class BuyTicket implements Runnable{
    // 票
    private int ticketNums = 10;
    boolean flat = true; // 外部停止方式
    @Override
    public void run() {
        // 买票
        while (flat){
            try {
                buy();
                // 模拟延时
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

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

        // 买票
        System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
    }
}

c3424e99dfabf8376dbe6da1ec2edf7.jpg

package dom01;

public class test2 {
    public static void main(String[] args) {
        // 账户
        Account account = new Account(100,"结婚基金");

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

        you.start();
        gail.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){
        super(name);
        this.account = account;
        this.drawingmoney = drawingmoney;
    }
    // 取钱

    @Override
    public void run() {
        synchronized (account){
            if (account.money-drawingmoney<0){
                System.out.println(Thread.currentThread().getName()+"钱不够取不了");
                return;
            }
        }
        
        // 卡内余额
        account.money = account.money- drawingmoney;
        // 你手里的钱
        nowmoney = nowmoney +drawingmoney;
        System.out.println(account.name+"余额为"+account.money);
        System.out.println(Thread.currentThread().getName()+"手里的钱"+nowmoney);
    }
}

死锁

5d2226a85e15d7bba589393b3e1f453.jpg

package syn;

// 死锁:多个线程互相持有对方需要的资源,然后形成僵持
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 girlname; // 使用化妆品的人

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

    @Override
    public void run() {
        // 化妆
        try {
            makeup();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    // 化妆,互相持有对方的锁,就是需要拿到对方的资源
    private void makeup() throws InterruptedException {
        if (choice == 0) {
            synchronized (lipstick) {
                // 获得口红的锁
                System.out.println(this.girlname + "获得口红的锁");
                Thread.sleep(1000);

                synchronized (mirror) {
                    // 一秒钟后想获得镜子
                    System.out.println(this.girlname + "获得镜子的锁");
                }
            }

        } else {
            synchronized (mirror) {
                // 获得口红的锁
                System.out.println(this.girlname + "获得镜子的锁");
                Thread.sleep(2000);

                synchronized (lipstick) {
                    // 一秒钟后想获得镜子
                    System.out.println(this.girlname + "获得口红的锁");
                }
            }

        }
    }
}    // 如此会导致程序锁死,不再往后执行

image.png

package syn;

// 死锁:多个线程互相持有对方需要的资源,然后形成僵持
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 girlname; // 使用化妆品的人

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

    @Override
    public void run() {
        // 化妆
        try {
            makeup();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    // 化妆,互相持有对方的锁,就是需要拿到对方的资源
    private void makeup() throws InterruptedException {
        if (choice == 0) {
            synchronized (lipstick) {
                // 获得口红的锁
                System.out.println(this.girlname + "获得口红的锁");
                Thread.sleep(1000);

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

//                synchronized (lipstick) {
//                    // 一秒钟后想获得镜子
//                    System.out.println(this.girlname + "获得口红的锁");
//                }
            }
            synchronized (lipstick) {
                // 一秒钟后想获得镜子
                System.out.println(this.girlname + "获得口红的锁");
            }
        }
    }
}  // 只要不互相抱着对方的锁,就不会卡死

d9fac6326304957b63257b627324ca5.jpg

Lock(锁)

c1b81cb13fc0898937d2b0e686b31e9.jpg

package syn;

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 ticketName = 10;

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

    @Override
    public void run() {
        while (true){
            try {
                lock.lock();// 加锁
                if (ticketName>0){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println(ticketName--);
                }else {
                    break;
                }
            }finally {
                // 解锁
                lock.unlock();
            }

        }
    }
}

书写规范

aadad664a2c673e46dbf8e9d4189e21.jpg

线程协作

线程通信

93e1a17e174dc58fc634051fe676cae.jpg

管程法

614dc2a476977e99511cd4b084c8e14.jpg

72839d1697bf2b8c188c5945e8bb8ec.jpg

package syn;

// 测试生产者消费者模型-->利用缓冲区解决:管程法

// 生产者,消费者,产品,缓冲区
public class TestPC {
    public static void main(String[] args) {
        SynContainer container = new SynContainer();

        new Productor(container).start();
        new Consumer(container).start();
    }
}
// 生产者
class Productor extends Thread{
    SynContainer container;
    public Productor(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("消费了"+container.pop().id+"只鸡");
        }
    }
}

// 产品
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) {
                throw new RuntimeException(e);
            }
            // 通知消费者消费,生产等待
        }
        // 如果没有满,就需要丢入产品
        chickens[count]=chicken;
        count++;
        // 可以通知消费者消费
        this.notify();
    }

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

}

信号灯法

package syn;

// 测试生产者消费者问题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{
    // 演员表演,观众等待
    // 观众观看,演员等待
    String voice;// 表演的节目
    boolean flag = true;

    // 表演
    public synchronized void play(String voice){
        if (!flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        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) {
                throw new RuntimeException(e);
            }
        }
        System.out.println("观看了:"+voice);
        // 通知演员表演
        this.notifyAll();
        this.flag = !this.flag;

    }
}

线程池

5a890ef6ab20337005bde313a34961a.jpg

使用线程池

da1a1040bc2ba93b4e2efdc3f6a6d50.jpg

package syn;

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());
    }
}