多线程详解学习笔记

狂神说Java:https://www.bilibili.com/video/BV1V4411p7EF

一、线程、进程、多线程

一个进程可以有多个线程。

说起进程,就不得不说下程序。程序是指令和数据的有序集合,其本身没有任何运行的含义,是一个静态的概念。而进程则是执行程序的一次执行过程,它是一个动态的概念。是系统资源分配的单位。

==通常在一个进程中可以包含若干个线程,当然一个进程中至少有一个线程,不然没有存在的意义。==线程是CPU调度和执行的的单

位。

注意:很多多线程是模拟出来的,真正的多线程是指有多个cpu。即多核,如服务器。如果是模拟出来的多线程,即在一个cpu的情况下,在同一个时间点,cpu只能执行一个代码。因为切换的很快,所以就有同时执行的错觉。

  • 线程就是独立的执行路径。
  • 在程序运行时,即使没有自己创建线程,后台也会有多个线程,如主线程、gc线程
  • main()称之为主线程,为系统的入口,用于执行整个程序。
  • 在一个进程中,如果开辟了多个线程,线程的运行由调度器安排调度。调度器是与操作系统紧密相关的,先后顺序是不能人为干预的。
  • 对同一份资源操作时,会存在资源抢夺的问题,需要加入并发控制。
  • 线程会带来额外的开销,如cpu调度时间、并发控制开销。
  • 每个线程在自己的工作内存交互,内存控制不当会造成数据不一致。

二、线程的创建 - 继承Thread类

3种方式:Thread类、Runnable接口Callable接口

Thread类

官方文档:
在这里插入图片描述1. 继承Thread类
2. 重写run()方法
3. 创建线程对象,调用
start()方法
启动线程

继承Thread创建线程

public class TestThread1 extends Thread{

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println("我在看代码===>" + i);
        }
    }

    // main线程,主线程
    public static void main(String[] args) {

        // 创建线程对象
        TestThread1 testThread1 = new TestThread1();
        // 调用start()方法开启线程
        testThread1.start();

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

}
我在学习多线程==>0
我在学习多线程==>1
我在学习多线程==>2
我在学习多线程==>3
我在学习多线程==>4
我在学习多线程==>5
我在看代码===>0
我在看代码===>1
我在学习多线程==>6
我在看代码===>2
我在看代码===>3
我在看代码===>4
我在看代码===>5
我在看代码===>6
我在看代码===>7
我在看代码===>8
我在看代码===>9
我在看代码===>10
我在看代码===>11
我在看代码===>12
我在看代码===>13
我在看代码===>14
我在学习多线程==>7
我在学习多线程==>8
我在看代码===>15
我在学习多线程==>9
我在学习多线程==>10
我在学习多线程==>11
我在学习多线程==>12
我在看代码===>16
我在看代码===>17
我在看代码===>18
我在学习多线程==>13
我在看代码===>19
我在学习多线程==>14
我在学习多线程==>15
我在学习多线程==>16
我在学习多线程==>17
我在学习多线程==>18
我在学习多线程==>19

Process finished with exit code 0

线程不一定立即执行,CPU调度安排。

三、案例:多线程下载图片

public class TestThread2 extends Thread{

    private String url;
    private String name;

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

    /**
     * 下载图片线程的执行体
     */
    @Override
    public void run() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url, name);
        System.out.println("下载了文件名为:" + name);
    }

    public static void main(String[] args) {

        TestThread2 thread1 = new TestThread2("https://img-blog.csdnimg.cn/20210305120636825.png","1.png");
        TestThread2 thread2 = new TestThread2("https://img-blog.csdnimg.cn/20210305121018539.png","2.png");
        TestThread2 thread3= new TestThread2("https://img-blog.csdnimg.cn/20210305121930543.png","3.png");

        thread1.start();
        thread2.start();
        thread3.start();

    }

}

/**
 * 下载器
 */
class WebDownloader{
    public void downloader(String url, String name){
        try {
            FileUtils.copyURLToFile(new URL(url), new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Io异常,downloader方法出现问题.");
        }
    }
}

结果:

下载了文件名为:2.png
下载了文件名为:3.png
下载了文件名为:1.png

Process finished with exit code 0

四、线程的创建 - 实现Runnable接口

  1. 实现Runnable接口
  2. 重写run()方法
  3. 创建线程对象,执行线程需要丢入Runnable接口实现类调用start()方法启动线程。
public class TestThread3 implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println("我在看代码===>" + i);
        }
    }

    // main线程,主线程
    public static void main(String[] args) {

        // 创建Runnable接口实现类对象
        TestThread3 testThread3 = new TestThread3();
        // 创建线程对象,通过线程对象来开启我们的线程,代理
        new Thread(testThread3).start();

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

}

结果:

我在学习多线程==>0
我在学习多线程==>1
我在学习多线程==>2
我在学习多线程==>3
我在学习多线程==>4
我在学习多线程==>5
我在学习多线程==>6
我在学习多线程==>7
我在学习多线程==>8
我在学习多线程==>9
我在学习多线程==>10
我在看代码===>0
我在看代码===>1
我在看代码===>2
我在看代码===>3
我在看代码===>4
我在看代码===>5
我在看代码===>6
我在看代码===>7
我在看代码===>8
我在看代码===>9
我在看代码===>10
我在看代码===>11
我在看代码===>12
我在看代码===>13
我在看代码===>14
我在看代码===>15
我在学习多线程==>11
我在学习多线程==>12
我在学习多线程==>13
我在学习多线程==>14
我在学习多线程==>15
我在学习多线程==>16
我在学习多线程==>17
我在看代码===>16
我在看代码===>17
我在看代码===>18
我在看代码===>19
我在学习多线程==>18
我在学习多线程==>19

Process finished with exit code 0

Thread类

在这里插入图片描述

Runnable接口

@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

五、继承Thread类和实现Runnable接口的对比

继承 Thread类

  • 子类继承Thread类具备多线程能力。
  • 启动线程:子类对象调用start()方法。
  • 不建议使用:避免OOP单继承局限性。

实现 Runnable接口

  • 实现接口Runnable具有多线程能力。
  • 启动线程:传入目标对象 + Thread对象调用start()方法。
  • 推荐使用:避免单继承局限性,灵活方便,方便同一个对象被多个线程使用。

六、初识并发问题

/**
 * @Desc 多个线程同时操作同一个对象
 * 买火车票
 * @Author HeJin
 * @Date 2021/3/9 20:28
 */
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) {
                e.printStackTrace();
            }

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

    }

}

结果:

黄牛党==>拿到了第8张票
小明==>拿到了第9张票
老师==>拿到了第10张票
老师==>拿到了第7张票
黄牛党==>拿到了第5张票
小明==>拿到了第6张票
小明==>拿到了第4张票
黄牛党==>拿到了第3张票
老师==>拿到了第3张票
老师==>拿到了第2张票		# 老师拿到第2张票
黄牛党==>拿到了第1张票
小明==>拿到了第2张票		# 小明也拿到第2张票

Process finished with exit code 0
老师==>拿到了第10张票
小明==>拿到了第9张票
黄牛党==>拿到了第8张票
小明==>拿到了第6张票
黄牛党==>拿到了第5张票
老师==>拿到了第7张票
老师==>拿到了第4张票
黄牛党==>拿到了第2张票
小明==>拿到了第3张票
黄牛党==>拿到了第1张票
老师==>拿到了第-1张票		# 出现 -1
小明==>拿到了第0张票

Process finished with exit code 0

多个线程操作同一个资源的情况下,线程不安全,数据紊乱。

七、龟兔赛跑

/**
 * @Desc 模拟龟兔赛跑
 * @Author HeJin
 * @Date 2021/3/10 9:16
 */
public class Race 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;
        }
        if (steps >= 100){
            winner = Thread.currentThread().getName();
            System.out.println("winner is " + winner);
            return true;
        }

        return false;
    }

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

}

八、线程的创建 - 实现Callable接口

  1. 实现Callable接口,需要返回值类型
  2. 重写Call方法,需要抛出异常
  3. 创建目标对象
  4. 创建执行服务
  5. 提交执行
  6. 获取结果
  7. 关闭服务
public class TestCallable implements Callable<Boolean> {

    private String url;
    private String name;

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

    /**
     * 下载图片线程的执行体
     */
    @Override
    public Boolean call() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url, name);
        System.out.println("下载了文件名为:" + name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        TestCallable thread1 = new TestCallable("https://img-blog.csdnimg.cn/20210305120636825.png","1.png");
        TestCallable thread2 = new TestCallable("https://img-blog.csdnimg.cn/20210305121018539.png","2.png");
        TestCallable thread3= new TestCallable("https://img-blog.csdnimg.cn/20210305121930543.png","3.png");

        // 创建执行服务
        ExecutorService service = Executors.newFixedThreadPool(3);
        // 提交执行
        Future<Boolean> r1 = service.submit(thread1);
        Future<Boolean> r2 = service.submit(thread2);
        Future<Boolean> r3 = service.submit(thread3);
        // 获取结果
        Boolean rs1 = r1.get();
        Boolean rs2 = r2.get();
        Boolean rs3 = r3.get();
        System.out.println(rs1);
        System.out.println(rs2);
        System.out.println(rs3);
        // 关闭服务
        service.shutdown();

    }

}

/**
 * 下载器
 */
class WebDownloader{
    public void downloader(String url, String name){
        try {
            FileUtils.copyURLToFile(new URL(url), new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Io异常,downloader方法出现问题.");
        }
    }
}

通过实现Callable接口创建线程的好处

  • 可以定义返回值
  • 可以抛出异常

九、Lambda表达式

为什么要使用Lambda表达式

  • 避免匿名内部类定义过多。
  • 可以让代码看起来很简洁。
  • 去掉了一堆没有意义的代码,只留下核心的逻辑。

其实质属于函数式编程的概念。

函数式接口的定义:任何接口,如果只包含唯一一个抽象方法,那么就是一个函数式接口。比如Runnable接口:

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

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

lambda表达式的推导

1、接口 + 实现类

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

/** 定义一个函数式接口 **/
interface ILike{
    void lambda();
}

/** 实现类 **/
class Like implements ILike{
    @Override
    public void lambda() {
        System.out.println("i like lambda");
    }
}

2、静态内部类

public class TestLambda1 {

    /** 静态内部类 **/
    static class Like implements ILike{
        @Override
        public void lambda() {
            System.out.println("i like lambda");
        }
    }

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

}

/** 定义一个函数式接口 **/
interface ILike{
    void lambda();
}

3、局部内部类

public class TestLambda1 {

    public static void main(String[] args) {
        /** 局部内部类 **/
        class Like implements ILike{
            @Override
            public void lambda() {
                System.out.println("i like lambda");
            }
        }

        ILike like = new Like();
        like.lambda();
    }

}

/** 定义一个函数式接口 **/
interface ILike{
  

4、匿名内部类

public class TestLambda1 {

    public static void main(String[] args) {

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

    }

}

/** 定义一个函数式接口 **/
interface ILike{
    void lambda();
}

5、lambda表达式简化

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

        /* lambda表达式简化 */
        ILike like = () -> {
            System.out.println("i like lambda");
        };
        like.lambda();

    }
}

/** 定义一个函数式接口 **/
interface ILike{
    void lambda();
}

带参数的lambda表达式

public class TestLambda2 {
    public static void main(String[] args) {
        Ilove ilove = (int a) -> {
            System.out.println("I love you===>" + a);
        };
        ilove.love(11);

        // 简化1
        ilove = (a) -> {
            System.out.println("I love you===>" + a);
        };
        ilove.love(22);

        // 简化2
        ilove = a -> {
            System.out.println("I love you===>" + a);
        };
        ilove.love(2233);

        // 简化3
        ilove = a -> System.out.println("I love you===>" + a);
        ilove.love(666);
    }
}

interface Ilove{
    void love(int a);
}

总结

  • lambda表达式只能有一行代码的情况下,才能去掉大括号,简化成一行。多行,使用代码块包括。
  • lambda表达式前提是接口为函数式接口
  • 多个参数也可以去掉参数类型,要去掉都去掉。必须加括号。

十、静态代理

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("我要结婚了,超开心!");
    }
}

/**
 * 代理角色:帮助你结婚
 */
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("结婚之后,收尾款");
    }
}
结婚之前,布置现场
我要结婚了,超开心!
结婚之后,收尾款

Process finished with exit code 0
  • 真实对象和代理对象都要实现同一个接口
  • 代理对象要代理真实角色
  • 代理对象可以做很多真实对象做不了的事情
  • 真实对象专注做自己的事情

静态代理和线程的对比

public class StaticProxy {
    public static void main(String[] args) {
        new Thread(() -> {
            System.out.println("我爱你");
        }).start();

        new WeddingCompany(new You()).happyMarry();
    }
}

发现实现Runnable接口创建线程的启动,底层原理就是静态代理

十一、线程状态

在这里插入图片描述
在这里插入图片描述

十二、线程方法

方法说明
setPriority(int newPriority)更改线程的优先级
static void sleep(long millis)在指定的毫秒数内让当前正在执行的线程体休眠
void join()等待该线程终止
static void yield()暂停当前正在执行的线程对象,并执行其他线程
void interrupt()中断线程,别用这个方式
boolean isAlive()测试线程是否处于活动状态

十三、停止线程

不推荐使用JDK提供的stop()、destroy()方法。已废弃。

在这里插入图片描述

推荐线程自己停止下来。建议使用一个标志位进行终止变量。当flag=false,则终止线程运行。

十四、线程休眠 - sleep

  • sleep(时间)指定当前线程阻塞的毫秒数
  • seep存在异常InterruptedException
  • sleep时间达到后线程进入就绪状态
  • seep可以模拟网络延时,倒计时等。
  • 每一个对象都有一个锁,sleep不会释放锁。

模拟网络延时

模拟网络延时:放大问题的发生性。

public class TestSleep implements Runnable{
    /** 票数 **/
    private int ticketNums = 10;

    @Override
    public void run() {
        while (true) {
            if (ticketNums <=0){
                break;
            }
            // 模拟延时
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(Thread.currentThread().getName() + "==>拿到了第" + ticketNums-- + "张票");
        }
    }

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

打印系统当前时间

public class TestSleep2 {
    public static void main(String[] args) {
        Date date = new Date(System.currentTimeMillis());
        while (true){
            try {
                Thread.sleep(1000);
                System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
                // 更新当前事件
                date = new Date(System.currentTimeMillis());
            } 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;
            }
        }
    }
}

十五、线程礼让 - yield

礼让线程,让当前正在执行的线程暂停,但不阻塞

将线程从运行状态转为就绪状态

让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()+"线程停止执行");
    }
}
a线程开始执行
b线程开始执行
b线程停止执行
a线程停止执行

Process finished with exit code 0

十六、线程强制执行 - 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 {
        // 启动我们的线程
        TestJoin testJoin = new TestJoin();
        Thread thread = new Thread(testJoin);

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

十七、线程状态观测

Thread. State

public static enum Thread.State
extends Enum<Thread.State>
A thread state. A thread can be in one of the following states:
NEW
A thread that has not yet started is in this state.
RUNNABLE
A thread executing in the Java virtual machine is in this state.
BLOCKED
A thread that is blocked waiting for a monitor lock is in this state.
WAITING
A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
TIMED_WAITING
A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
TERMINATED
A thread that has exited is in this state.
A thread can be in only one state at a given point in time. These states are virtual machine states which do not reflect any operating system thread states.

线程状态。线程可以处于以下状态之一:

  • NEW 尚未启动的线程处于此状态
  • RUNNABLE 在Java虚拟机中执行的线程处于此状态。
  • BLOCKED 被阻塞等待监视器锁定的线程处于此状态
  • WAITING 正在等待另一个线程执行特定动作的线程处于此状态
  • TIMED WAITING 正在等待另一个线程执行动作达到指定等待时间的线程处于此状态。
  • TERMINATED 已退出的线程处于此状态。

一个线程可以在给定时间点处于一个状态。这些状态是不反映任何操作系统线程状态的虚拟机状态。

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

    }
}

十八、线程优先级

Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行。
在这里插入图片描述
线程的优先级用数字表示,范围从1~10

  • Thread. MIN_PRIORTY=1
  • Thread. MAX_PRIORITY= 10
  • Thread. NORM_PRIORITY= 5

使用以下方式改变或获取优先级

  • getPriority(). setPriority(int xxx)

在这里插入图片描述

先设置优先级,再启动线程。

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(8);
        t5.start();

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

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

优先级低只是意味着获得调度的概率低。并不是优先级低就不会被调用了。这都是看CPU的调度

十九、守护线程 - daemon

线程分为用户线程守护线程。虚拟机必须确保用户线程执行完毕。虚拟机不用等待守护线程执行完毕。如:后

台记录操作日志、监控内存、垃圾回收等待。

public class TestDaemon {
    public static void main(String[] args) {
        God god = new God();
        You you = new You();

        Thread thread = new Thread(god);
        // 默认false,表示用户线程
        thread.setDaemon(true);
        // 上帝守护线程启动
        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");
    }
}

二十、线程同步机制

并发

多个线程操作同一个资源

并发:同一个对象多个线程同时操作。比如:上万人同时抢100张票、两个银行同时取钱等。

  • 现实生活中我们会遇到”同一个资源,多个人都想使用“的问题。比如食堂排队打饭,每个人都想吃饭,最天然的解决办法就是排队。一个个来。

  • 处理多线程问题时,多个线程访问同一个对象,并且某些线程还想修改这个对象。这时候我们就需要线程同步。线程同步其实就是一种等待机制,多个需要同时访问此对象的线程进入这个对象的等待池形成队列,等待前面线程使用完毕,下一个线程再使用。

队列和锁

形成条件:队列 + 锁

线程同步

由于同一进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突问题。为了保证数据在方法中被访问时的正确性,在访问时加入锁机制

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){
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void buy() throws InterruptedException {
        // 判断是否有票
        if (ticketNums <= 0){
            flag = false;
            return;
        }
        Thread.sleep(100);
        // 买票
        System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNums--+"张票");
    }
}
// 出现-1
牛逼的你们拿到了第-1张票

Process finished with exit code 0    

// 多个人拿一张票
牛逼的你们拿到了第2张票
可恶的黄牛党拿到了第2张票    

测试发现有多个人拿到同一张票和出现了负数,线程不安全

每个线程在自己的工作内存交互,内存控制不当会造成数据不一致

银行取钱

public class UnsafeBank {
    public static void main(String[] args) {
        Account account = new Account(100,"结婚基金");
        Drawing you = new Drawing(account, 50,"你");
        Drawing girlFriend = new Drawing(account, 100,"girlFriend");

        you.start();
        girlFriend.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() {
        // 判断有没有钱
        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);
    }
}

运行结果不一样,可能是CPU多线程执行了。

结果1:

结婚基金余额为:50
你手里的钱:50
结婚基金余额为:-50
girlFriend手里的钱:100

Process finished with exit code 0

结果2:

结婚基金余额为:-50
结婚基金余额为:-50
girlFriend手里的钱:100
你手里的钱:50

Process finished with exit code 0

线程不安全的集合

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

Process finished with exit code 0

同时有两个或者多个线程一瞬间同时操作了同一个位置,也就是把多个数据添加到了同一个位置,会覆盖掉,list的长度就会减小。

二十二、同步方法及同步块

由于我们可以通过 private关键字来保证数据对象只能被方法访问。所以我们只需要针对方法提出一套机制,这套机制就是synchronized关键字。它包括两种用法**:synchronized方法**和 synchronized块

同步方法

同步方法: public synchronized void method(int args){}

synchronized方法控制对对象的访问,每个对象对应一把锁,每个synchronized方法都必须获得调用该方法的对象的锁才能执行。否则线程会阻塞。方法一旦执行,就独占该锁,直到该方法返回才释放锁。后面被阻塞的线程才能获得这个锁,继续执行。

缺陷:若将一个大的方法申明为synchronized将会影响效率

方法里面需要修改的内容才需要锁,锁得太多,浪费资源。

同步块

同步块:synchronized(obj){}

obj称之为同步监视器

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

同步监视器的执行过程

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

安全的买票

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){
            try {
                buy();
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * synchronized 同步方法。锁得是this
     */
    private synchronized void buy() throws InterruptedException {
        // 判断是否有票
        if (ticketNums <= 0){
            flag = false;
            return;
        }
        // 买票
        System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNums--+"张票");
    }
}
苦逼的我拿到了第10张票
可恶的黄牛党拿到了第9张票
牛逼的你们拿到了第8张票
苦逼的我拿到了第7张票
可恶的黄牛党拿到了第6张票
牛逼的你们拿到了第5张票
苦逼的我拿到了第4张票
可恶的黄牛党拿到了第3张票
牛逼的你们拿到了第2张票
苦逼的我拿到了第1张票

Process finished with exit code 0

安全的取钱

public class UnsafeBank {
    public static void main(String[] args) {
        Account account = new Account(1000,"结婚基金");
        Drawing you = new Drawing(account, 50,"你");
        Drawing girlFriend = new Drawing(account, 100,"girlFriend");

        you.start();
        girlFriend.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;
            }

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

结果1:

结婚基金余额为:950
你手里的钱:50
结婚基金余额为:850
girlFriend手里的钱:100

Process finished with exit code 0

结果2:

结婚基金余额为:900
girlFriend手里的钱:100
结婚基金余额为:850
你手里的钱:50

Process finished with exit code 0

安全的集合

public class UnsafeList {
    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());
    }
}
10000

Process finished with exit code 0

当去掉延时的时候,发现打印的小于10000。这是因为打印语句是由主线程执行的,主线程虽然执行完了(电脑性能太好),但是往集合中添加元素的线程还没有执行完。这样打印结果就小于10000了。但是此时还是线程安全。

二十三、CopyOnWriteArrayList

java.util.concurrent包下。CopyOnWriteArrayList是线程安全的。
在这里插入图片描述

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

Process finished with exit code 0

二十四、死锁

多个线程各自占有一些共享资源,并且互相等待其他线程占有的资源才能运行。从而导致两个或者多个线程都在等待对方释放资源,都停止执行的情形。某一个同步块同时拥有两个以上对象的锁时,就可能会发生死锁的问题。

多个线程互相抱着对方需要的资源,然后形成僵持。

**
 * @Desc 死锁:多个线程互相抱着对方需要的资源,然后形成僵持。
 * @Author HeJin
 * @Date 2021/3/10 19:07
 */
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;

    public 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);
                // 1秒钟后想获得镜子
                synchronized (mirror){
                    System.out.println(this.girlName + "获得镜子的锁");
                }
            }
        } else {
            synchronized (mirror){
                System.out.println(this.girlName + "获得镜子的锁");
                Thread.sleep(2000);
                // 1秒钟后想获得镜子
                synchronized (lipstick){
                    System.out.println(this.girlName + "获得口红的锁");
                }
            }
        }
    }
}

测试会发现程序卡死:

灰姑凉获得口红的锁
白雪公主获得镜子的锁

修改makeUp()方法:

private void makeUp() throws InterruptedException {
    if (choice == 0){
        // 获得口红的锁
        synchronized (lipstick){
            System.out.println(this.girlName + "获得口红的锁");
            Thread.sleep(1000);
        }
        // 1秒钟后想获得镜子
        synchronized (mirror){
            System.out.println(this.girlName + "获得镜子的锁");
        }
    } else {
        synchronized (mirror){
            System.out.println(this.girlName + "获得镜子的锁");
            Thread.sleep(2000);
        }
        // 1秒钟后想获得镜子
        synchronized (lipstick){
            System.out.println(this.girlName + "获得口红的锁");
        }
    }
}
灰姑凉获得口红的锁
白雪公主获得镜子的锁
白雪公主获得口红的锁
灰姑凉获得镜子的锁

Process finished with exit code 0

产生死锁的四个必要条件

  • 互斥条件:一个资源每次只能被一个进程使用。
  • 请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放。
  • 不剥夺条件:进程已获得的资源,在末使用完之前,不能强行剥夺。
  • 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系。

上面列出了死锁的四个必要条件,我们只要想办法破坏其中的任意一个或多个条件就可以避免死锁发生。

二十五、Lock锁

从JDK5.0开始,Java提供了更强大的线程同步机制——通过显式定义同步锁对象来实现同步。同步锁使用Lock对象充当。

java. util. concurrent.locks.Lock接口是控制多个线程对共享资源进行访问的工具。锁提供了对共享资源的独占访问,每次只能有一个线程对Lock对象加锁,线程开始访问共享资源之前应先获得Lock对象。

ReentrantLock类(可重入锁)实现了Lock,它拥有与 synchronized相同的并发性和内存语义。在实现线程安全的控制中,比较常用的是 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{
    int ticketNums = 10;

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

    @Override
    public void run() {
        while (true){
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 加锁
            lock.lock();
            try {
                if (ticketNums > 0){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNums--+"张票");
                } else {
                    break;
                }
            }  finally {
                // 解锁
                lock.unlock();
            }
        }
    }
}

结果:

老师拿到了第10张票
小明拿到了第9张票
黄牛党拿到了第8张票
老师拿到了第7张票
小明拿到了第6张票
黄牛党拿到了第5张票
老师拿到了第4张票
小明拿到了第3张票
黄牛党拿到了第2张票
老师拿到了第1张票

Process finished with exit code 0

synchronized与Lock的对比

  • Lock是显式锁(手动开启和关闭锁,别忘记关闭锁) 。synchronized是隐式锁,出了作用域自动释放。
  • Lock只有代码块锁,synchronized有代码块锁和方法锁
  • 使用Lock锁,JVM将花费较少的时间来调度线程,性能更好。并且具有更好的扩展性(提供更多的子类)。

优先使用顺序

Lock > 同步代码块(已经进入了方法体,分配了相应资源) > 同步方法(在方法体之外)

二十六、线程协作 - 生产者消费者问题

应用场景:生产者和消费者问题

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

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

  • 对于生产者,没有生产产品之前,要通知消费者等待。而生产了产品之后,又需要马上通知消费者消费。
  • 对于消费者,在消费之后,要通知生产者已经结束消费,需要生产新的产品以供消费。
  • 在生产者消费者问题中,仅有 synchronized是不够的:
    • synchronized可阻止并发更新同一个共享资源,实现了同步。
    • synchronized不能用来实现不同线程之间的消息传递(通信)。

Java提供了几个方法解决线程之间的通信问题

方法名作用
wait()表示线程一直等待,直到其他线程通知,与seep不同。会释放锁
wait(long timeout)指定等待的毫秒数。
notify()唤醒一个处于等待状态的线程。
notifyAll()唤醒同一个对象上所有调用wait()方法的线程,优先级比较高的线程优先调度。

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

二十七、管程法

并发协作模型生产者/消费者模式 管程法

  • 生产者:负责生产数据的模块(可能是方法、对象、线程、进程)。
  • 消费者:负责处理数据的模块(可能是方法、对象、线程、进程)。
  • 缓冲区:消费者不能直接使用生产者的数据,他们之间有个缓冲区。

生产者将生产好的数据放入缓冲区,消费者从缓冲区拿出数据。

管程法:生产者、消费者、产品、缓冲区

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++) {
            container.push(new Chicken(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 Chicken extends Thread{
    /** 产品编号 **/
    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;
    }

}
生产了==>0只鸡
生产了==>1只鸡
生产了==>2只鸡
生产了==>3只鸡
生产了==>4只鸡
生产了==>5只鸡
生产了==>6只鸡
生产了==>7只鸡
生产了==>8只鸡
生产了==>9只鸡
生产了==>10只鸡
消费了===>4只鸡
生产了==>11只鸡
消费了===>10只鸡
生产了==>12只鸡

二十八、信号灯法

信号灯法,标志位解决。

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++) {
            this.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;
    }
}
演员表演了《大本营播放中》
观看了《大本营播放中》
演员表演了《抖音:记录美好生活》
观看了《抖音:记录美好生活》
演员表演了《大本营播放中》
观看了《大本营播放中》
演员表演了《抖音:记录美好生活》
观看了《抖音:记录美好生活》

二十九、线程池

使用线程池的原因

背景:经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大

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

好处:

  • 提高响应速度(减少了创建新线程的时间)。
  • 降低资源消耗(重复利用线程池中线程,不需要每次都创建)。
  • 便于线程管理。
    • corePoolsize:核心池的大小。
    • maximumPoolSize:最大线程数。
    • keepAliveTime:线程没有任务时最多保持多长时间后会终止。

使用线程池

JDK5.0起提供了线程池相关AP:ExecutorServiceExecutors

ExecutorService:真正的线程池接口。常见子类 ThreadPoolExecutor

void execute( Runnable command):执行任务/命令,没有返回值,一般用来执行Runnable。
<T> Future<T> submit(Callable<T> task):执行任务,有返回值,一般用来执行Callable。

void shutdown():关闭连接池。

Executors:工具类、线程池的工厂类,用于创建并返回不同类型的线程池。

public class TestPool {
    public static void main(String[] args) {
        // 1、创建服务,创建线程池.参数为线程池大小
        ExecutorService service = Executors.newFixedThreadPool(10);
        // 2、执行
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());
        // 3、关闭连接
        service.shutdown();
    }
}

class MyThread implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}

结果:

pool-1-thread-1
pool-1-thread-2
pool-1-thread-3
pool-1-thread-4
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,我来详细解释一下多线程。 在一个程序中,通常会有多个任务需要同时执行,而且有些任务可能需要很长的时间才能完成。如果所有的任务都在一个线程中执行,就会出现程序“卡住”的情况,即程序处于一种等待状态,无法响应用户的操作,用户体验非常差。为了解决这个问题,就需要使用多线程技术。 多线程是指在一个程序中同时运行多个线程,每个线程都可以独立执行不同的任务。每个线程都有自己的堆栈、局部变量和程序计数器等线程私有的资源,但是它们共享进程的其他资源,比如全局变量和静态变量等。多线程可以让程序更加高效,能够同时处理多个任务,提高系统的响应速度和并发能力。 在 C# 中,可以使用 System.Threading 命名空间中的 Thread 类来创建和管理线程。下面是使用 Thread 类创建和启动一个线程的示例代码: ``` using System; using System.Threading; public class Program { public static void Main() { Thread t = new Thread(new ThreadStart(DoWork)); t.Start(); } public static void DoWork() { // 线程要执行的任务 } } ``` 上面的代码中,我们创建了一个名为 t 的线程,并将其启动。线程要执行的任务定义在 DoWork 方法中。 在多线程编程中,需要注意线程之间的同步问题,以避免出现数据竞争和死锁等问题。比如,多个线程可能同时访问同一个共享变量,如果不加以控制,就会出现数据竞争的问题。C# 中提供了多种线程同步机制,比如 lock、Monitor、Semaphore 等,可以用来保护共享资源,避免数据竞争问题的发生。 此外,多线程还有一些常见的问题,比如线程池的使用、线程的优先级、线程的异常处理等等。需要开发人员了解和掌握这些知识,才能写出可靠、高效的多线程程序。 总之,多线程是一种非常重要的编程技术,可以提高程序的效率和性能,但是也需要开发人员具备一定的编程经验和技能,才能正确地使用它。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值