Java多线程(入门系列)

狂神说笔记整理

一、线程简介与核心概念

Java多线程(入门系列)_第1张图片
Java多线程(入门系列)_第2张图片

二、线程创建

Java多线程(入门系列)_第3张图片

  • Callable暂作了解,不是目前的重点
  • 继承Thread类
package kssManyThread;

public class day1 extends Thread{
     
    // 1.继承Thread类


    // 2.重写run方法
    @Override
    public void run() {
     
        for(int i = 0;i<20;i++)
            System.out.println("我在看代码--"+i);
    }

    public static void main(String[] args) {
     
        //创建一个线程对象
        day1 day = new day1();
        day.start();//如果这里是run, 则会先执行run方法
        for(int i = 0;i<20;i++){
     
            System.out.println("我在学习多线程--"+i);
        }
    }
}

  • 继承Runnable接口
package kssManyThread;

public class day1 implements Runnable{
     
// 继承Runnable接口

    //重写run方法 将执行线程丢入runnable接口实现
    @Override
    public void run() {
     
        for(int i = 0;i<10;i++){
     
            System.out.println("我在看代码--"+i);
        }
    }
    public static void main(String[] args) {
     

        //创建runnable接口实现对象
        day1 day = new day1();

        //创建线程对象, 通过线程对象来开启我们的线程
        Thread thread = new Thread(day);

        thread.start();
    }
}

推荐使用第二种继承Runnable接口的方法,因为这样的话使用会更灵活,方便一个对象被多个线程使用


  • 火车票案例
  • 多个线程同时操作一个对象会不安全
package kssManyThread;

// 多个线程同时操作一个对象
// 买火车票的方法

// 发现多个线程操作同一个资源的情况下, 线程不安全
public class day1 implements Runnable{
     

    //票数
    private int ticksNums = 10;

    @Override
    public void run() {
     
        while (true){
     

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

            System.out.println(Thread.currentThread().getName()+"拿到了"+ticksNums--+"票");
            if (ticksNums<=0){
     
                break;
            }
        }
    }
    public static void main(String[] args) {
     
        day1 day = new day1();
        new Thread(day, "小明").start();
        new Thread(day, "老师").start();
        new Thread(day, "黄牛").start();
    }
}

  • 模拟龟兔赛跑
package kssManyThread;

// 模拟龟兔赛跑
public class day1 implements Runnable{
     

    //胜利者
    private static String winner;

    @Override
    public void run() {
     
        for(int i = 0;i<=100;i++){
     

            // 模拟兔子休息
            if (Thread.currentThread().getName().equals("兔子")&& i%10==0){
     
                try {
     
                    Thread.sleep(1);
                } catch (InterruptedException e) {
     
                    e.printStackTrace();
                }
            }
            //判断比赛是否结束
            boolean flag = gameOver(i);
            if (flag){
      //为真,就停止程序;
                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) {
     

        day1 day = new day1();

        new Thread(day,"兔子").start();
        new Thread(day,"乌龟").start();
    }
}

Java多线程(入门系列)_第4张图片

  • 静态代理模式
package kssManyThread;

// 静态代理模式: 真实对象跟代理对象都要实现同一个接口,代理对象要代理真实角色,就是要有一个参数把真实角色传进去
// 代理对象可以做很多真实对象做不了的事情

public class day1  {
     
    public static void main(String[] args) {
     

        //自己结婚
        You you = new You();
        you.HappyMarry();

        new Thread( ()-> System.out.println("我爱你")).start();

        //代理结婚
        new WeddingCompany(new You()).HappyMarry();
        //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 after() {
     
        System.out.println("结婚之后,布置收尾款");
    }

    private void before() {
     
        System.out.println("结婚之前, 布置现场");
    }
}
  • Lambda表达式
    Java多线程(入门系列)_第5张图片
    Java多线程(入门系列)_第6张图片
  • 案例
package kssManyThread;



public class day1 {
     

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


        // 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表达式
package kssManyThread;



public class day1 {
     



    public static void main(String[] args) {
     




        ILike like = (int a)->{
     
            System.out.println("i like lambda"+a);
        };
        like.lambda(2);

    }
}

// 1.实现一个函数式接口
interface ILike{
     
    void lambda(int a);
}

// 2.实现类
class Like implements ILike{
     

    @Override
    public void lambda(int a) {
     
        System.out.println("i like lambda"+a);
    }
}
  • lambda再简化
package kssManyThread;
public class day1 {
     
    public static void main(String[] args) {
     
        ILike like = null;

        like = a-> System.out.println("i like lambda"+a);
        like.lambda(2);

        //进一步简化 可以没有int(参数类型),可以没有括号(),花括号也可以去掉
        // 注意前提, 代码只有一行,花括号才能简化
        //接口必须为函数式接口
        // 多个参数可以去掉类型,要去掉都去掉,但括号要打上去

    }
}

// 1.实现一个函数式接口
interface ILike{
     
    void lambda(int a);
}

// 2.实现类
class Like implements ILike{
     

    @Override
    public void lambda(int a) {
     
        System.out.println("i like lambda"+a);
    }
}

三、线程状态

Java多线程(入门系列)_第7张图片
-------------------------------------------------------------------------------------------------------------------------------Java多线程(入门系列)_第8张图片
Java多线程(入门系列)_第9张图片
Java多线程(入门系列)_第10张图片

  • 线程停止案例
package kssManyThread;

import java.util.Date;

// 1、建议线程正常停止,利用次数,不建议死循环
    // 2、建议使用标志位
    // 3、不要使用stop或destroy等JDK不建议使用的方法
public class day1 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) {
     
            day1 day = new day1();
            new Thread(day).start();

            for (int i = 0; i < 1000; i++) {
     
                System.out.println("main"+i);
                if (i==900){
     //调用自己写的stop方法让线程停止
                    day.stop();
                    System.out.println("线程停止");
                }
            }
     }
}

Java多线程(入门系列)_第11张图片

  • 模拟倒计时
package kssManyThread;

// 模拟倒计时
public class day1{
     

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

        while(true){
     
            Thread.sleep(1000);
            System.out.println(num--);
            if(num<=0){
     
                break;
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
     
        tenDown();
    }
}
  • 打印系统当前时间(前一秒)
package kssManyThread;

import java.text.SimpleDateFormat;
import java.util.Date;

// 打印系统当前时间
public class day1{
     

    public static void tenDown() throws InterruptedException {
     
        int num = 10;
        Date startTime = new Date(System.currentTimeMillis());//获取系统当前时间

        while (true){
     
            Thread.sleep(1000);
            System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
            startTime = new Date(System.currentTimeMillis());//更新时间
        }
    }

    public static void main(String[] args) throws InterruptedException {
     
        tenDown();
    }
}

Java多线程(入门系列)_第12张图片

  • 案例
package kssManyThread;

// 测试礼让线程, 礼让不一定成功,看CPU心情
public class day1 {
     




    public static void main(String[] args) throws InterruptedException {
     
        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()+"线程停止执行");
    }
}

Java多线程(入门系列)_第13张图片

package kssManyThread;

//测试join
public class day1 implements Runnable {
     
    public static void main(String[] args) throws InterruptedException {
     
       day1 day = new day1();

       Thread thread = new Thread(day);
       thread.start();

       //主线程
        for (int i = 0; i < 500; i++) {
     
            if (i==200){
     
                thread.join();//插队,即主线程让thread线程插队
            }
            System.out.println("mian"+i);
        }
    }

    @Override
    public void run() {
     
        for (int i = 0; i < 1000; i++) {
     
            System.out.println("线程vip来了");
        }
    }
}

  • 观察测试线程的状态
package kssManyThread;

// 观察测试线程的状态
public class day1 {
     

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

    }
}

四、线程优先级

Java多线程(入门系列)_第14张图片

  • 案例
package kssManyThread;

// 线程优先级高并不一定先执行
public class day1 implements Runnable{
     

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

    public static void main(String[] args) {
     
        //主线程默认优先级 5
        System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());

        day1 day = new day1();
        Thread thread1 = new Thread(day);
        Thread thread2 = new Thread(day);
        Thread thread3 = new Thread(day);
        Thread thread4 = new Thread(day);
        Thread thread5 = new Thread(day);
        Thread thread6 = new Thread(day);


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

        thread2.setPriority(1);
        thread2.start();

        thread3.setPriority(4);
        thread3.start();

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

        //thread5.setPriority(-1); 会报错,下面也是如此
        //thread5.start();

        //thread6.setPriority(11);
        //thread6.start();
    }
}

五、守护线程

Java多线程(入门系列)_第15张图片

package kssManyThread;

// 测试守护线程  上帝守护着你
public class day1 {
     
    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");
    }
}

六、线程同步

Java多线程(入门系列)_第16张图片
Java多线程(入门系列)_第17张图片
Java多线程(入门系列)_第18张图片
Java多线程(入门系列)_第19张图片

package kssManyThread;

// 不安全的买票
public class day1 {
     
    public static void main(String[] args) {
     
       BuyTickets station = new BuyTickets();

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

class BuyTickets implements Runnable{
     

    boolean flag = true;//外部停止

    //票
    private int ticketNum = 10;
    @Override
    public void run() {
     
        //买票
        while (flag){
     
            try {
     
                buy();
            } catch (InterruptedException e) {
     
                e.printStackTrace();
            }
        }
    }

    private void buy() throws InterruptedException {
     

        //模拟延时 放大问题的发生性
        Thread.sleep(100);

        //判断是否有票
        if (ticketNum<=0) return;
        else {
     
            System.out.println(Thread.currentThread().getName()+"拿到"+ticketNum--);
        }
    }
}

Java多线程(入门系列)_第20张图片
Java多线程(入门系列)_第21张图片

package kssManyThread;

// 不安全的买盘
public class day1 {
     
    public static void main(String[] args) {
     
       BuyTickets station = new BuyTickets();

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

class BuyTickets implements Runnable{
     

    boolean flag = true;//外部停止

    //票
    private int ticketNum = 10;
    @Override
    public void run() {
     
        //买票
        while (flag){
     
            try {
     
                buy();
            } catch (InterruptedException e) {
     
                e.printStackTrace();
            }
        }
    }

    //同步方法 锁的是this  锁同步块也一样,只要传入要锁的对象就行了,即这个要锁的是要改变的东西
    private synchronized void buy() throws InterruptedException {
     

        //模拟延时 放大问题的发生性
        Thread.sleep(100);

        //判断是否有票
        if (ticketNum<=0) {
     
            flag = false;
            return;
        }
        else {
     
            System.out.println(Thread.currentThread().getName()+"拿到"+ticketNum--);
        }
    }
}

Java多线程(入门系列)_第22张图片

package kssManyThread;

// 死锁:多个线程互相抱着对方需要的资源,然后形成僵持
public class day1 {
     
    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) {
     
            e.printStackTrace();
        }
    }


    // 化妆,互相持有对方的锁,就是要拿到对方的资源
    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 + "获得口红的锁");
                }
            }
        }
    }
}

Java多线程(入门系列)_第23张图片
Java多线程(入门系列)_第24张图片

package kssManyThread;

import java.util.concurrent.locks.ReentrantLock;

// lock锁
public class day1 {
     
    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 tickets = 10;

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

    @Override
    public void run() {
     
        while (true){
     

            try{
     
                lock.lock();//加锁
                if (tickets>0){
     
                    try {
     
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
     
                        e.printStackTrace();
                    }
                    System.out.println(tickets--);
                }else{
     
                    break;
                }
            }finally {
     

                lock.unlock();//解锁
            }

        }
    }


}

Java多线程(入门系列)_第25张图片

七、线程通信

Java多线程(入门系列)_第26张图片
Java多线程(入门系列)_第27张图片
Java多线程(入门系列)_第28张图片
Java多线程(入门系列)_第29张图片
Java多线程(入门系列)_第30张图片

  • 管程法
package kssManyThread;

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


import java.awt.*;

public class day1 {
     

    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++) {
     
            try {
     
                container.push(new Chicken(i));
            } catch (InterruptedException e) {
     
                e.printStackTrace();
            }
            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++) {
     
            try {
     
                System.out.println("消费了第"+ container.pop().id+"只鸡");
            } catch (InterruptedException e) {
     
                e.printStackTrace();
            }
        }
    }
}

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

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


//缓冲区
class SynContainer{
     

    //需要一个容器大小
    Chicken[] chickens = new Chicken[10];

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

    //生产者放入chanp
    public synchronized void push(Chicken chicken) throws InterruptedException {
     

        //如果容器满了,就要等待消费者消费
        if (count== chickens.length){
     
            //通知消费者消费,生产者等待
            this.wait();
        }
        //如果没满,就要丢入产品
        chickens[count] = chicken;
        count++;

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


    }

    //消费者消费产品
    public synchronized Chicken pop() throws InterruptedException {
     
        //判断能否消费
        if (count==0){
     
            //等待生产者生产,消费者等待
            this.wait();
        }

        //如果可以消费
        count--;
        Chicken chicken = chickens[count];



        //吃完了,通知生产者生产
        return chicken;
    }
}
  • 信号灯
package kssManyThread;

public class day1 {
     

    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){
     
                try {
     
                    this.tv.play("快乐大本营播放ing");
                } catch (InterruptedException e) {
     
                    e.printStackTrace();
                }
            }else{
     
                try {
     
                    this.tv.play("抖音,记录美好生活");
                } catch (InterruptedException e) {
     
                    e.printStackTrace();
                }
            }
        }
    }
}

//消费者--观众

class Watcher extends Thread{
     
    TV tv;
    public Watcher(TV tv){
     
        this.tv = tv;
    }

    @Override
    public void run() {
     
        for (int i = 0; i < 20; i++) {
     
            try {
     
                tv.Watch();
            } catch (InterruptedException e) {
     
                e.printStackTrace();
            }
        }
    }
}

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

    //表演
    public  synchronized void play(String voice) throws InterruptedException {
     

        if (!flag){
     
            //演员等待
            this.wait();
        }
        System.out.println("演员表演了:"+voice);

        //通知观众观看
        this.notifyAll();//唤醒
        this.voice = voice;
        this.flag = !this.flag;
    }

    //观看
    public synchronized void Watch() throws InterruptedException {
     
        if (flag){
     
            this.wait();
        }
        System.out.println("观看了:"+voice);

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

八、线程池

Java多线程(入门系列)_第31张图片
Java多线程(入门系列)_第32张图片

package kssManyThread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//线程池
public class day1 {
     

    public static void main(String[] args) {
     
        // 1.创建线程池
        ExecutorService service = Executors.newFixedThreadPool(10);//参数为线程池大小

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

        //2.关闭连接
        service.shutdown();

    }
}

class  MyThead implements Runnable{
     

    @Override
    public void run() {
     

            System.out.println(Thread.currentThread().getName());

    }
}

你可能感兴趣的:(Java多线程笔记整理,java,多线程)