Java threads created in two ways:
1. Thread class by inheritance, the rewriting Thread run () method, the thread running in a logical wherein
2. By implementing Runnable interface, the Thread class instantiation
In practical applications, we often use multi-threading, such as the station's ticketing system, the station ticket window is equivalent to each individual threads. When we do this system, we might think of two ways to achieve, inheritance Thread class or implement Runnable interface, and now look at the two results of these two methods to achieve.
A: inheritance Thread class
Results are as follows: multiple windows to complete multiple tasks
Two: the way you implement Runnable
Results are as follows: multiple windows to complete a task
Three: a comparison between the two
Why two different results appear na? We might as well be a metaphor, in fact, on top of the program,
Inherit the Thread class, we come up with three things that is equivalent to selling 10 tickets three tasks were given to three windows, each doing what they each sell 10 tickets each to complete their respective tasks, because MyThread thread class inheritance, so when the new MyThread, and in the creation of three objects at the same time creates three threads;
Implement Runnable, it is to come up with the equivalent of a task to sell 10 tickets together to complete the three windows, new MyThread equivalent to creating a task, and then instantiate three Thread, create three threads that is scheduled to perform three windows .
When we are new may be confused inherit the Thread class and Runnable interface to achieve multi-threaded, in fact, after the contact we will find it is an entirely different multi-threading, multiple threads each one is to complete their task, a multiple threads together to complete a task.
In fact, to achieve a task to do with multiple threads can also be used to implement the Thread class inherits just too much trouble, we usually use to achieve Runnable interface to achieve, clear and concise.
In most cases, if you want to override the run () method, without overwriting other Thread methods, you should use the Runnable interface. This is important, because unless the programmer intends on modifying or enhancing the fundamental behavior of the class, it should not create a sub-class this (Thread).
Reprinted: https: //www.cnblogs.com/zhaosq/p/9882102.html