Which method do you choose to create a thread ?, Which method to create a thread?
Aside from the thread pool, there are two ways to create a thread:
The first way to create a thread:
Features (defects) of this method: the thread tasks and threads are bound together.
Example:
Sell tickets at the same time in four windows,
Multiple Threads are used because they are the same.
Four threads are created to sell tickets.
Because they all sell tickets, the tasks of the four threads are the same.
You only need to define a class to inherit the Thread.
Class Ticket extends Thread {private static int num = 50; // defined as static. The four threads share 50 tickets. Public void run () {while (num> 0) System. out. println (Thread. currentThread (). getName () + "... sale... "+ num --) ;}} class Maipiao {public static void main (String [] args) {Ticket win1 = new Ticket (); Ticket win2 = new Ticket (); ticket win3 = new Ticket (); Ticket win4 = new Ticket (); win1.start (); win2.start (); win3.start (); win4.start ();}}
This method of thread creation is not available. Why? For more information, see
The second way to create a thread:
This method is characterized by describing thread tasks, that is, object-oriented, so as to achieve the separation of thread tasks and thread objects. It is no longer important for a Thread to execute any task. As long as the subclass object implementing the Runnable interface can be passed as a parameter to the Thread constructor, this method is more flexible.
The second method also has the advantage of implementing interfaces without affecting the inheritance of other parent classes.
// This class is only used to describe the task of a thread and has nothing to do with the thread. Class Ticket implements Runnable {private int num = 50; public void run () {while (num> 0) System. out. println (Thread. currentThread (). getName () + "... sale... "+ num --) ;}} class Maipiao {public static void main (String [] args) {Ticket t = new Ticket (); Thread win1 = new Thread (t ); thread win2 = new Thread (t); Thread win3 = new Thread (t); Thread win4 = new Thread (t); win1.start (); win2.start (); win3.start (); win4.start ();}}
Through the code, we can conclude that:
Why does the second method of creating a thread solve the ticket selling problem?
The first way to create a thread: the thread and the thread task are bound together. After four threads are created, four resources are created.
The second method is to create a thread: the thread and the thread task are separated. You only need to create one task and let the four threads execute it separately.