Summary of core knowledge of multithreading (1)-to achieve the correct posture of multithreading

Multi-threaded core knowledge summary

1. Realize the correct posture of multithreading

1. How many ways are there to achieve multithreading?

There are only two kinds of official documents.

  1. Declare a subclass of Thread
public class ThreadStyle extends Thread{
    
    

    @Override
    public void run() {
    
    
        System.out.println("用Thread类实现线程");
    }

    public static void main(String[] args) {
    
    
        new ThreadStyle().start();
    }
}
  1. Declare a class that implements the Runnable interface
public class RunnableStyle implements Runnable{
    
    

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

    @Override
    public void run() {
    
    
        System.out.println("用Runnable方法实现线程");
    }
}

The comparison of the two methods
implements the Runnable method better
for the following reasons:

  1. From the perspective of code architecture, the specific tasks performed, that is, the content of the run method code, should be decoupled from the creation and operation mechanism of the thread, that is, the Thread class.
  2. If you use the Thread class, you can only create a new thread every time you want to perform a task, and the loss of creating an independent thread is relatively large (create, execute, destroy), and if you use Runnable, you can use tools such as thread pools , This can greatly reduce the loss.
  3. After inheriting the Thread class, since Java does not support double inheritance, this class cannot inherit other classes, which greatly limits the scalability.

The essential comparison of the two methods

  1. Implement Runnable-finally call target.run()
  2. Inherit Thread-rewrite the entire run () method

2. Use two methods at the same time: a summary of the correct implementation method

public class BothRunnableThread {
    
    

    public static void main(String[] args) {
    
    
        new Thread(new Runnable() {
    
    
            @Override
            public void run() {
    
    
                System.out.println("我来自Runnable");
            }
        }) {
    
    
            @Override
            public void run() {
    
    
                System.out.println("我来自Thread");
            }
        }.start();
    }
}

The result of running this code is

我来自Thread

From an object-oriented perspective, consider
that the run method in Thread completely covers the run method in Runnable, so the overridden method is executed, which is the run method in Thread.

to sum up:

  1. Implementation threads can generally be divided into two categories

  2. To be precise, there is only one way to create a thread, that is, to construct the Thread class, and there are two forms of implementing the thread's execution unit.

    1. Implement the run method of the Runnable interface and pass the Runnable instance to the Thread class
    2. Override the run method of Thread (inherit the Thread class)

3. Typical misconceptions

  1. Thread pool creation of threads is also a new way to create threads
/**
 1. 描述:     线程池创建线程的方法
 */
public class ThreadPool{
    
    

    public static void main(String[] args) {
    
    
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 1000; i++) {
    
    
            executorService.submit(new Task() {
    
    
            });
        }
    }
}
class Task implements Runnable {
    
    

    @Override
    public void run() {
    
    
        try {
    
    
            Thread.sleep(500);
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName());
    }
}

The essence of thread pool creation is the same as new Thread()

  1. Creating threads through Callable and FutureTask is also a new way to create threads.
    Insert picture description hereInsert picture description hereAccording to the implementation diagram of the class, it can be seen that they are essentially implemented by runnable and thread.

  2. Timer

/**
 * 描述:     定时器创建线程
 */
public class DemoTimmerTask {
    
    

    public static void main(String[] args) {
    
    
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
    
    
            @Override
            public void run() {
    
    
                System.out.println(Thread.currentThread().getName());
            }
        }, 1000, 1000);
    }
}

View the source code, essentially a kind of packaging

4. Common interview questions

How many ways to implement threads, there are 5 ideas

  1. From different angles, there will be different answers
  2. The classic answer is two (Thread, Runnable)
  3. Look at the principle, the two essences are the same (construct the Thread class)
  4. Specifically expand and talk about other methods (thread pool, timer, anonymous inner class, Lambda expression)
  5. in conclusion

Guess you like

Origin blog.csdn.net/qq_45092505/article/details/108849174