Comparison between inheriting thread class and implementing runnable interface in Java

There are two ways to create threads in Java:

1. By inheriting the thread class, override the run () method of thread and put the logic of thread running in it

2. Instantiate the thread class by implementing the runnable interface

In practical applications, we often use multithreading, such as the station ticket system. Each ticket outlet of the station is equivalent to each thread. When we do this system, we may think of two ways to implement it, inherit the thread class or implement the runnable interface. Now let's take a look at the two results of these two ways.

The operation results are as follows:

The code for implementing runnable interface is as follows:

The operation results are as follows:

Why did this happen. We might as well make an analogy. In fact, the program just started,

If we inherit the thread class, we are equivalent to taking out three things, that is, three tasks of selling 10 tickets to three windows. They do their own things and sell their own tickets to complete their own tasks. Because myThread inherits the thread class, three threads are created while creating three objects in new myThread;

Realizing runnable is equivalent to taking out a task of selling 10 tickets to three people to complete together. New myThread is equivalent to creating a task, then instantiating three threads and creating three threads, that is, arranging three windows to execute.

It is shown as follows:

When we first came into contact, we may be confused about inheriting the thread class and implementing the runnable interface to realize multithreading. In fact, after contacting, we will find that these are completely two different multithreads. One is that multiple threads complete their own tasks respectively, and the other is that multiple threads complete a task together.

In fact, when implementing a task with multiple threads, it can also be implemented by inheriting the thread class, which is just troublesome. Generally, we use the runnable interface to implement it, which is concise and clear.

In most cases, if you want to override only the run () method and not the other thread methods, you should use the runnable interface. This is important because you should not create subclasses for a class (thread) unless the programmer intends to modify or enhance the basic behavior of the class.

Thank you for reading, hope to help you, thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>