工作中线程的启动

2021/8/24 13:05:34

本文主要是介绍工作中线程的启动,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

我们平时学习线程 , 继承Thread类实现Runnable接口 这么写 仅供学习

public class Test02 {

    public static void main(String[] args) {
        Book2 book = new Book2();
        new Thread(book, "A").start();
        new Thread(book, "B").start();
        new Thread(book, "C").start();
    }
}


class Book2 implements Runnable{
     private int num = 60;

    @Override
    public void run() {
        for (int i = 0; i < 60; i++) {
            System.out.println(Thread.currentThread().getName()+"卖出了第" + (num--)+ "本剩余" + num + "本");
        }
    }
}


在平时的工作中 ,我们几乎不会这样去开启线程 线程就是单独的一个资源类 不做任何多余的操作

我们实现了Runnable接口 他就变成了一个线程类 这样违背了我们OOP原则

我们记住 解耦 : 我们只需要把需要操作的资源 扔到线程中即可

我们需要操作的资源 多线程操作同一资源类 把资源类放入线程中
lombok表达式

public class Test01 {

    public static void main(String[] args) {
        Book book = new Book();

        new Thread(() -> {
            for (int i = 0; i < 60; i++) {
                book.sell();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 60; i++) {
                book.sell();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 60; i++) {
                book.sell();
            }
        }, "C").start();
    }
}


class Book{
    private int num = 60;

    public void sell(){
        System.out.println(Thread.currentThread().getName()+"卖出了第" + (num--)+ "本剩余" + num + "本");
    }

}

这样 Book类就是一个纯粹的资源类不受任何因素的影响



这篇关于工作中线程的启动的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程