Two ways to create threads in Java

Source: Internet
Author: User

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:
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:
t = new Thread (this, "Demo thread");
This is indicated by the preceding statement in this object that 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:
Child Thread:thread[demo Thread,5,main]
Main Thread:5
Child Thread:5
Child Thread:4
Main Thread:4
Child Thread:3
Child Thread:2
Main Thread:3
Child Thread:1
Exiting child thread.
Main Thread:2
Main thread:1
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:
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.

Transferred from the Micro-Science Court (http://www.weixueyuan.net/view/6027.html)

Two ways to create threads in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.