It's almost 2021, you still don't know how to achieve multithreading?

1. Why is there this article

Time flies, back to 2017, the end of the year; I just finished self-learning programming and the three major frameworks, it can be said to be  full of confidence, and the sword refers to the offer.

As everyone knows, in the first interview , I was taught a lesson by a Xiao Yang (not too old) interviewer ; these years have passed, and it is still fresh in my memory.

So I'm such a dish?  It's been two years before I know how to implement multithreading

 

  • Xiao Yang: Come, talk about multithreading
  • Aniu: A thread is an execution unit in a process. . .
  • Xiao Yang: There are several ways to implement multithreading
  • Ah Niu: 2 kinds (without hesitation, who doesn’t know yet!!)
  • Xiao Yang: What is the difference between these two
  • Aniu: Yes. . . (Suddenly B)

In this way, I was panicking, accepting all kinds of torture from Xiao Yang, and finally ended with " go back and wait for the notice ";

After the interview, although I can vaguely guess the result, I am also eager to go to heaven, the balance is tilted;

A Niu waited for a few days,  but after three autumns, it ended with  GG .

2. Talk about how to achieve multithreading

Small partners know that a program  does not jump statements  under the premise, are  from top to bottom  in sequence.

Now I want to design a program, " code code " and "  watch blockbuster movies (decent people)  ", how to design it?

So I'm such a dish?  It's been two years before I know how to implement multithreading

 

First of all, to solve the above problems, we have to  talk about multi-threading , then we must first understand what  threads  and  processes are

In the concurrency module  of the " Java Programming Thoughts " book  , there are two sentences to describe processes and threads

Process : Refers to an application program running in memory. Each process has an independent memory space. The process is actually the one-time execution of the program and the basic unit of the system running the program.

Thread : refers to a single sequential control flow in a process

Translation : Thread is actually an execution unit in the process, responsible for the execution of the program in the current process

Although these two sentences are a bit abstract, they speak the essence of threads and processes.

Come on, let’s take a look at the " process " in the editor system 

So I'm such a dish?  It's been two years before I know how to implement multithreading

 

Next, let’s take a look at the " thread " in Xiaobian Computer Manager 

So I'm such a dish?  It's been two years before I know how to implement multithreading

 

After understanding threads and processes, multithreading can be described as " so easy "

Next, briefly talk about several ways to implement multithreading, don’t " two years later "

Three, inherit the Thread class, understand

It’s time to " install B " again, come and take a look at  the source code of the Thread class

So I'm such a dish?  It's been two years before I know how to implement multithreading

 

Next, look at the " start() method " of the Thread class

So I'm such a dish?  It's been two years before I know how to implement multithreading

 

It can be seen from the source code that the Thread class is essentially an instance of the Runnable interface.

Therefore, the only way to start a thread is through the start() method of the Thread class. The start() method is a  native method , which will start a new thread and execute the run() method.

Come, next, the whole point SAO operation

First, create the  TestThread class (decent people, don't think too much)

/**
 * Create By CodeCow on 2020/8/3.
 */
public class TestThread {

    public static void main(String[] args) {
        MyThread mt = new MyThread("新线程————看大片");
        //开启新线程
        mt.start();
        //在主方法中执行for循环
        for (int i = 0; i < 5; i++) {
            System.out.println("main线程————撸代码,没意思。。" + i);
        }
    }

    //继承Thread类
    public static class MyThread extends Thread {
        //定义指定线程名称的构造方法
        public MyThread(String name) {
            //调用父类的String参数的构造方法,指定线程的名称(原理:利用继承特点,将线程名称传递)
            super(name);
        }

        //重写run方法,定义线程要执行的代码
        @Override
        public void run() {
            for (int j = 0; j < 5; j++) {
                //getName()方法 来自父亲(就是Thread类中,获取当前线程名称方法)
                System.out.println(getName() + " :好刺激哟,不行了,快、快。。" + j);
            }
        }
    }
}

Next, let's  run TestThread to see what the result is

Connected to the target VM, address: '127.0.0.1:56321', transport: 'socket'
main线程————撸代码,没意思。。0
main线程————撸代码,没意思。。1
新线程————看大片 :好刺激哟,不行了,快、快。。0
main线程————撸代码,没意思。。2
新线程————看大片 :好刺激哟,不行了,快、快。。1
main线程————撸代码,没意思。。3
新线程————看大片 :好刺激哟,不行了,快、快。。2
新线程————看大片 :好刺激哟,不行了,快、快。。3
新线程————看大片 :好刺激哟,不行了,快、快。。4
main线程————撸代码,没意思。。4
Disconnected from the target VM, address: '127.0.0.1:56321', transport: 'socket'

It’s not difficult to find that the "  Code Thread " and "  Looking Block Thread  " were executed five times each

Therefore, to start the thread in this way, directly use  your own class to inherit the Thread class and rewrite his run() method  to start the thread and execute the run() method defined by yourself . This operation is not 6!

So I'm such a dish?  It's been two years before I know how to implement multithreading

 

Fourth, realize the Runnable interface, understand

This time, the editor will not " install B " and will show you  the source code of the Runnable class.

So I'm such a dish?  It's been two years before I know how to implement multithreading

 

It is not difficult to find from the source code that the Runnable interface has been available since " Java1.0 ", and there is only one abstract method run() inside.

Therefore: To start a thread, it is necessary to implement the Runnable interface and rewrite its run() method.

  • Note: Because Java does not support multiple inheritance, if your class has inherited the other classes, to start the thread will implement Runnable interface and override its run () method  Come, practical operation of the whole wave

First, create the TestRunnable class and implement the Runnable interface

/**
 * Create By CodeCow on 2020/8/3.
 */
public class TestRunnable implements Runnable{

    //重写run()方法, 写自己需要的代码
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            //currentThread() 返回对当前正在执行的线程对象的引用
            System.out.println(Thread.currentThread().getName()+" :好刺激哟,不行了,快、快。。" + i);
        }
    }

    public static void main(String[] args) {
        //创建自定义类对象 线程任务对象
        TestRunnable mr = new TestRunnable();
        //创建线程对象
        Thread t = new Thread(mr, "新线程————看大片(正经人别多想)");
        t.start();
        for (int i = 0; i < 5; i++) {
            System.out.println("main线程————撸代码,没意思。。" + i);
        }
    }
}

Next, let's  run TestRunnable and see what the result will be

Connected to the target VM, address: '127.0.0.1:56275', transport: 'socket'
main线程————撸代码,没意思。。0
新线程————看大片(正经人别多想) :好刺激哟,不行了,快、快。。0
main线程————撸代码,没意思。。1
新线程————看大片(正经人别多想) :好刺激哟,不行了,快、快。。1
main线程————撸代码,没意思。。2
新线程————看大片(正经人别多想) :好刺激哟,不行了,快、快。。2
main线程————撸代码,没意思。。3
新线程————看大片(正经人别多想) :好刺激哟,不行了,快、快。。3
main线程————撸代码,没意思。。4
新线程————看大片(正经人别多想) :好刺激哟,不行了,快、快。。4
Disconnected from the target VM, address: '127.0.0.1:56275', transport: 'socket'

It is not difficult to find that the "  Code Thread " and " Looking Block Thread " have also been executed five times each. Stabilized

So I'm such a dish?  It's been two years before I know how to implement multithreading

 

Stable is stable, but many people will definitely think that this is not written Low;

Low, Low to death, after all, JDK is almost out of 15 , even 8 " Lambda " still can't use it! ! !

Come and see  the SAO operation using  Lambda expression + anonymous inner class

/**
 * Create By CodeCow on 2020/8/3.
 */
public class TestRunnableByLambda {

    public static void main(String[] args) {
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("新线程————看大片(别多想) :好刺激哟,不行了,快、快。。" + i);
            }
        }).start();
        for (int i = 0; i < 5; i++) {
            System.out.println("main线程————撸代码,没意思。。" + i);
        }
    }
}

The result is self-evident, and it is also that the " code thread " and the " watch blockbuster thread " were executed five times each

So I'm such a dish?  It's been two years before I know how to implement multithreading

 

Of course, in actual development, it is not as simple as the previous article "Promise me, don't if/else check request parameters anymore".

In other words, it is not as simple as 3 + 2-5 * 0

If there is a demand: the asynchronous execution thread needs to return a value to the current thread after the execution is completed, and the current thread needs to rely on this value to do some other business operations!

What to do now! Don't panic, Callable is here

Five, Callable Understand

Similarly, let everyone take a look at  the source code of the Callable class

So I'm such a dish?  It's been two years before I know how to implement multithreading

 

It can be seen that the Callable interface   began to appear in Java 1.5 , and  there is only one call () method with a return value.

So, the question is, how to write a thread button with a return value?

Calm down and watch my performance

First, create the TestCallable class and implement the Callable interface

/**
 * Create By CodeCow on 2020/8/3.
 */
@Slf4j
public class TestCallable implements Callable<String> {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        TestCallable testCallable = new TestCallable();
        Future<String> future = executorService.submit(testCallable);
        log.info("future: " + future.get()); //get会阻塞
        executorService.shutdown();
    }

    @Override
    public String call() throws Exception {
        return "带含有返回值的线程";
    }
}

Next, we  run TestCallable to see the result

Connected to the target VM, address: '127.0.0.1:57004', transport: 'socket'
03:45:08.723 [main] INFO com.codecow.mini.test.TestCallable - future: 带含有返回值的线程
Disconnected from the target VM, address: '127.0.0.1:57004', transport: 'socket'

It's not hard to see, see what. . . .

postscript

Well, now you first talk to here, this article merely  initiate  it, shallow talked to achieve " multi-threaded " in several ways.

Secondly, if I could read similar articles two years ago, and " read more books, read more newspapers, less bragging B, and sleep more ", I would not have passed by "Xiao Yang". Hey! Two years.

Guess you like

Origin blog.csdn.net/m0_46757769/article/details/109586534