Several ways to implement threads __ Threads

Source: Internet
Author: User
Tags thread class

Java uses the thread class to represent threads, and all thread objects must be instances of the thread class or its subclasses.
Java can create threads in three different ways, as follows:

1. Create thread by inheriting thread class

/** * (1). First, define a class to inherit the thread parent class, overriding the run () method in the parent class.
 Add specific task code or processing logic to the run () method.
 * (2). Directly create an object of the ThreadTest class, or you can take advantage of polymorphism, and the variable is declared as the type of the parent class.
 * (3). Call the Start method, the thread starts, and the implicit call to the run () method.
                */public class ThreadTest extends thread{public void run () {while (true) {try { Thread.Sleep (1000);/Hibernate 1000 milliseconds (1 seconds)} catch (Interruptedexception e) {E.printstacktrace
            ();

            System.out.println ("Print Current thread name:" +thread.currentthread (). GetName ()); 
        Print the current thread name, this is used here to get, at some point it is not applicable, it is recommended to use the above method System.out.println ("Call getName method through this, print thread name:" +this.getname ()); The call public static void main (string[] args) {ThreadTest thread1= is demonstrated in the Main method New ThreadTest ();//Create the first thread object Thread1.start (); Start the first thread threadtest thread2=new threadtest ();//Create a second thread object Thread2.start (); Start a second thread} 

2, through the implementation of Runnable interface to create a thread

/**
 * (1). Defines a class that implements the Runnable interface and overrides the Run () method in the interface. Add specific task code or processing logic to the run () method.
 * (2). Creates an object for the Runnable interface implementation class.
 * (3). To create an object of the ThreadTest class, you need to encapsulate the object of the previous Runnable interface implementation class. (interface can implement multiple inheritance)
 * (4). Call the Thread object's start () method, start the threads/public

class ThreadTest implements runnable{  

    @ Override public  
    Void Run () {while  
        (true) {
            try {
                thread.sleep (1000);/Hibernate 1000 milliseconds (1 seconds)
            } catch ( Interruptedexception e) {
                e.printstacktrace ();
            }
            System.out.println ("Print Current thread name:" +thread.currentthread (). GetName ());
        }  

    Demonstrates calling public
    static void Main (string[] args) {  
        thread theard=new thread (new ThreadTest ()) in the Main method;//Creating a Thread object C21/>theard.start ();  Start thread
    }  
}  

3. Creating threads through callable and future

/** * (1) creates the implementation class for the callable interface and implements the call () method, which acts as a thread execution body and has a return value.
 * (2) Create an instance of the callable implementation class and use the Futuretask class to wrap the callable object, which encapsulates the return value of the call () method for the callable object.
 * (3) Create and start a new thread using the Futuretask object as target of the thread object.
* (4) Call the Futuretask object's Get () method to obtain the return value after the execution of the child thread/import java.util.concurrent.Callable;
Import Java.util.concurrent.FutureTask; public class ThreadTest implements callable<integer>{@Override the public Integer call () throws Exception  
        {int count = 0;  
        for (int i=0;i<=10;i++) {count=count+i;
      System.out.println ("Print Current thread name:" +thread.currentthread (). GetName ()); return count; return value}//demo calling public static void main (string[] args) throws Exception {futuretask& in the Main method  
        lt;integer> thread = new futuretask<> (new ThreadTest ()); New Thread (thread, "This is the threading name"). Start (); Start Thread System.out.println (Thread.get ()); Print thread return value}} 

summarized as follows

Using the Inheritance Thread class:
(1) Advantages: Simple writing, if you need to access the current thread, without using the Thread.CurrentThread () method, use this directly, you can get the current thread.
(2) Disadvantage: Because the thread class has inherited the thread class, no other parent class can be inherited. The

implementation of Runnable Interface:
(1) Advantages: The thread class only implements the Runable interface, but also can inherit other classes. In this way,
         multiple threads can share the same target object, so it is very suitable for multiple identical threads to handle the same resource, so that the
         CPU code and data can be separated to form a clear model to better embody the object-oriented thinking.
(2) Disadvantage: Programming is slightly more complex, and if you need to access the current thread, you must use the Thread.CurrentThread () method.

I'll put the following three implementations directly together, the code is as follows:

Import java.util.concurrent.Callable;

Import Java.util.concurrent.FutureTask; public class Threaddemo {public static void main (string[] args) {//======= creation thread first (thread is a class that inherits the run

                Nable interface) ======= thread thread = new Thread () {@Override the public void Run () {//This method writes our business code
                    while (true) {try {thread.sleep (1000);/Hibernate 1000 milliseconds (is 1 seconds)
                    catch (Interruptedexception e) {e.printstacktrace (); ///Print the current thread name System.out.println ("Create thread first, print thread name:" +thread.currentthread (). GetName (

                    )); Print the current thread name, this is used here to get, at some point it is not applicable, it is recommended to use one of the above methods System.out.println ("Create threading method, call GetName method through this, print thread name:" +
                This.getname ());

        }
            }
        }; Thread.Start ()//Start thread//======= Create thread first end =======//======= Create thread mode two start (RunnAble is an interface) ======= thread thread2 = new Thread (new Runnable () {@Override public void run ( {//This method writes our business code while (true) {try {thread.sleep (1000);/hibernate 1
                    000 milliseconds (1 seconds)} catch (Interruptedexception e) {e.printstacktrace (); ///Print the current thread name System.out.println ("Create thread two, print thread name:" +thread.currentthread

                    (). GetName ());

        TODO this way is not suitable for printing 2 of the way above through this to invoke the method that gets the current thread name}}); Thread2.start ()//Start thread//======= Create thread mode two end =======//======= Create thread three start ======= Futureta sk<integer> thread3 = new futuretask<> (new callable<integer> () {@Override Publ  
                IC Integer Call () throws Exception {int count = 0; for (int i=0;i<=10;i++) {COunt=count+i;
                ///Print the current thread name System.out.println ("Create threading mode three, print thread name:" +thread.currentthread (). GetName ()); return count;  

        Return value}}); New Thread (THREAD3, "This is the thread name"). Start ()//boot thread try {System.out.println ("Create thread three, print return value:" + thread3.get ());
        Print return value} catch (Exception e) {e.printstacktrace ();
 //======= Create thread method three end =======}}

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.