In most cases, one thread is created by instantiating a thread object. Java is defined in two ways:
- Implement Runnable interface;
- You can inherit the thread class.
The following two sections describe each of these methods in turn.
Implementing the Runnable Interface
The simplest way to create a thread is to create a class that implements the Runnable interface. Runnable Abstracts an execution code unit. You can create threads for each object by implementing the Runnable interface method. To implement the Runnable interface, a class only needs to implement a simple method of run (), which declares the following:
public void Run ()
You can define code in run () to build a new thread. It is important to understand that the run () method can invoke other methods, refer to other classes, and declare variables like the main thread. The only difference is that run () establishes another concurrent thread execution entry in the program. When run () returns, the thread ends.
After you have created a class that implements the Runnable interface, you instantiate an object of the thread class inside the class. The Thread class defines several constructors. We will use the following:
Thread (Runnable threadob, String threadname)
In this constructor, Threadob is an instance of implementing the Runnable interface class. This defines the starting point for thread execution. The name of the new thread is defined by ThreadName.
After a new thread is established, it does not run until it calls its start () method, which is defined in the thread class. Essentially, start () executes a call to run (). The Start () method is declared as follows:
1 void Start ()
The following example is to create a new thread and start it to run:
1 //Create a second thread.2 classNewthreadImplementsRunnable {3 Thread t;4 Newthread () {5 //Create A new, second thread6t =NewThread ( This, "Demo Thread");7SYSTEM.OUT.PRINTLN ("Child thread:" +t);8T.start ();//Start the thread9 }Ten One //This was the entry point for the second thread. A Public voidrun () { - Try { - for(inti = 5; i > 0; i--) { theSystem.out.println ("Child Thread:" +i); -Thread.Sleep (500); - } -}Catch(interruptedexception e) { +System.out.println ("Child interrupted.")); - } +System.out.println ("Exiting child Thread.")); A } at } - - classThreaddemo { - Public Static voidMain (String args[]) { - NewNewthread ();//Create a new thread - Try { in for(inti = 5; i > 0; i--) { -System.out.println ("Main Thread:" +i); toThread.Sleep (1000); + } -}Catch(interruptedexception e) { theSystem.out.println ("Main thread interrupted.")); * } $System.out.println ("Main thread exiting."));Panax Notoginseng } -}
In the Newthread constructor, the new thread object is created by the following statement:
1 New Thread (This, "Demo Thread");
through the preceding statement this indicates that in the this object you want the new thread to call the run () method. Then, start () is called to start the execution of the thread with the run () method. This causes the child thread for loop to start executing. After the call to start (), the Newthread constructor returns to main (). When the main thread is restored, it reaches the for loop. Two threads continue to run, sharing the CPU until their loop ends. The output of the program is as follows:
1 child Thread:thread[demo thread,5,main] 2 Main thread:5 3 child thread:5< Span style= "color: #008080;" > 4 child Thread:4 5 Main thread:4 6 Child Thread:3 child Thread:2 8 Main Thread:3 child Thread:110 exiting child thread. 11 main thread:212 Main Thread:113 Main thread exiting.
As mentioned earlier, in a multithreaded program, the main thread must usually be the last one to end the run. In fact, some older JVMs might "hang" the Java Runtime system if the main thread ends before the child threads. The procedure above guarantees the end of the main thread, since the main thread sleeps for 1000 milliseconds while the child thread is only 500 milliseconds. This causes the child thread to end before the main thread ends. In short, you'll see a better way to wait for the thread to end.
Extending the Thread
Another way to create a thread is to create a new class to extend the thread class, and then create an instance of the class. When a class inherits the thread, it must overload the run () method, which is the entry for the new thread. It must also call the start () method to start a new thread execution. The following procedure overrides the preceding program with the extended thread class:
1 //Create A second thread by extending thread2 classNewthreadextendsThread {3 Newthread () {4 //Create A new, second thread5 Super("Demo Thread");6SYSTEM.OUT.PRINTLN ("Child thread:" + This);7Start ();//Start the thread8 }9 Ten //This was the entry point for the second thread. One Public voidrun () { A Try { - for(inti = 5; i > 0; i--) { -System.out.println ("Child Thread:" +i); theThread.Sleep (500); - } -}Catch(interruptedexception e) { -System.out.println ("Child interrupted.")); + } -System.out.println ("Exiting child Thread.")); + } A } at - classExtendthread { - Public Static voidMain (String args[]) { - NewNewthread ();//Create a new thread - Try { - for(inti = 5; i > 0; i--) { inSystem.out.println ("Main Thread:" +i); -Thread.Sleep (1000); to } +}Catch(interruptedexception e) { -System.out.println ("Main thread interrupted.")); the } *System.out.println ("Main thread exiting.")); $ }Panax Notoginseng}
The program generates the same output as the previous version. A child thread is generated by instantiating an Newthread object that derives from the thread class. Note The call of super () in Newthread. The method calls the following form of the thread constructor:
1 Public Thread (String threadname)
Here, ThreadName specifies the thread name.
Choose the Right method
Here, you'll wonder why there are two ways to create a child thread in Java, which is better. All the problems are attributed to one point. The thread class defines several methods that can be overloaded by derived classes. For all methods, the only one that must be overloaded is the run () method. This is of course the same approach required to implement the Runnable interface. Many Java programmers think that classes should be extended only when they are enhanced or modified. Therefore, if you do not overload the other methods of thread, it is best to implement only the Runnable interface. It's up to you to decide. However, in other parts of this chapter, we apply classes that implement the Runnable interface to create threads.
Series Articles:
Java know how much (top)
Java know how much (interface) interface
Java knows how much (40) the difference between an interface and an abstract class
Java know how much (41) generic explanation
Java know how much (42) the range of generic wildcard characters and type parameters
Java know how much (43) Exception Handling Basics
Java know how much (44) exception type
Java know how much (45) uncaught exceptions
How much Java knows (the) use of try and catch
Java know how much (47) use of multiple catch statements
Java knows how much (in) the nesting of Try statements
Java know how much (a) throw: Exception throws
Java know how many () Java throws clauses
Java knows how many (or) finally
Java know how much (52) built-in exceptions
Java know how much (53) Use Java to create your own exception subclasses
Java know how much (54) assertion detailed
Java know how many (55) threads
Java know how much (56) threading ModelJava know how much (57) main thread
Java know how much (58) thread Runnable interface and thread class explanation