Examples of multithreaded programming in Java _java

Source: Internet
Author: User

Java creation thread (Runnable interface and thread Class)
In most cases, create a thread by instantiating a thread object. Java defines two ways:

    1. Implement Runnable interface;
    2. You can inherit the thread class.

Each of these methods is described in the following sequence.
Implement Runnable interface

The easiest way to create a thread is to create a class that implements the Runnable interface. Runnable abstracts an execution unit of code. You can create a thread for each object by implementing the Runnable interface. To implement the Runnable interface, a class only needs to implement a simple method of run (), the method declares as follows:

  public void Run ()


In run () you can define code to build a new thread. Understanding the following is essential: the run () method can invoke other methods, reference other classes, and declare variables as the main thread does. The only difference is that run () establishes another concurrent thread execution entry in the program. When run () is returned, 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 created, it does not run until it is called the start () method, which is defined in the thread class. In essence, start () performs 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 running:

Create a second thread.
  Class Newthread implements Runnable {Thread T;
    Newthread () {//Create a new, second thread t = new Thread (this, "Demo thread");
    SYSTEM.OUT.PRINTLN ("Child thread:" + t); T.start ();
  Start the thread}//This are the entry point for the second thread.
        public void Run () {try {to (int i = 5; i > 0; i--) {System.out.println ("Child Thread:" + i);
      Thread.Sleep (500);
    The catch (Interruptedexception e) {System.out.println ("Child interrupted.");
  } System.out.println ("Exiting child thread.");
      } class Threaddemo {public static void main (String args[]) {new Newthread ()//Create a new thread try {
        for (int i = 5; i > 0; i--) {System.out.println ("Main Thread:" + i);
      Thread.Sleep (1000);
    The catch (Interruptedexception e) {System.out.println ("Main thread Interrupted.");
  } System.out.println ("Main thread exiting.");}
}

 

In the Newthread constructor, the new thread object is created by the following statement::

  t = new Thread (this, Demo thread);


This indicates that you want the new thread to invoke the run () method in the This object. Then the start () is invoked, and the execution of the thread starts with the run () method. This causes the child thread for loop to begin execution. After calling 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 multithreaded programs, the main thread must be the last one to end the run. In fact, some old JVMs, if the main thread ends before the child, the Java runtime system may "hang". The preceding procedure guarantees the end of the main thread, because the main thread sleeps 1000 milliseconds and 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.
Extend 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 thread, it must overload the run () method, which is the entry of the new thread. It must also invoke the start () method to start a new thread execution. The preceding program is overridden with the extended thread class:

Create a second thread by extending thread class Newthread extends Thread {newthread () {//Create a new, secon
    D Thread Super ("Demo thread");
    SYSTEM.OUT.PRINTLN ("Child thread:" + this); Start ();
  Start the thread}//This are the entry point for the second thread.
        public void Run () {try {to (int i = 5; i > 0; i--) {System.out.println ("Child Thread:" + i);
      Thread.Sleep (500);
    The catch (Interruptedexception e) {System.out.println ("Child interrupted.");
  } System.out.println ("Exiting child thread."); 
      } class Extendthread {public static void main (String args[]) {new Newthread ()//Create a new thread try {
        for (int i = 5; i > 0; i--) {System.out.println ("Main Thread:" + i);
      Thread.Sleep (1000);
    The catch (Interruptedexception e) {System.out.println ("Main thread Interrupted.");
  } System.out.println ("Main thread exiting.");

 }
}

The program produces the same output as the previous version. A child thread is generated by the instantiated Newthread object, which derives from the thread class. Note the call to Super () in Newthread. The method invokes the following form of the thread constructor:

  Public Thread (String threadname)


Here, ThreadName specifies the thread name.
Choose the right method

Here, you must be wondering why Java has two ways to create child threads, which is better. All the problems are attributable to a 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 believe that classes should be extended only when they are strengthened or modified. Therefore, if you do not overload other methods of thread, it is best to implement only the Runnable interface. It's up to you, of course. However, in other parts of this chapter, we apply classes that implement the Runnable interface to create threads.

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.