Three ways to create threads pros and cons

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.
First, inherit thread class Create threads class
1. Rewrite the Run method. The method body of the run () method represents the task that the thread needs to complete.
2. Create an instance of the thread subclass.
3. Call the Thread object's start () method to start the thread.

public class TestCode1 extends Thread
{
    private int i;
    public void Run ()
    {for
        (; i<100;i++)
        {
            System.out.println (getName () + "" +i);
        }


    public static void Main (string[] args) 
    {for
        (int i=0;i<100;i++)
        {
            System.out.println ( Thread.CurrentThread (). GetName () + "" +i);
            if (i==20) {
                new TestCode1 (). Start ();
                New TestCode1 (). Start ();}}}

Second, implement runnable interface to create thread class
1. Define the implementation class for the runnable and rewrite the Run () method.
2. Create an instance of the Runnable implementation class and use this as target for thread to create an object that is the real thread object.

public class TestCode2 implements Runnable
{
    private int i;
    public void Run ()
    {A for
        (; i<100;i++)
        {System.out.println (
            thread.currentthread (). GetName () + "" + i);
        }


    public static void Main (string[] args) 
    {for
        (int i=0;i<100;i++)
        {
            System.out.println ( Thread.CurrentThread (). GetName () + "" +i);
            if (i==20) {
                TestCode2 test=new TestCode2 ();
                New Thread (test, 1). Start ();
                New Thread (test, 2). Start ();}}}


Iii. creating threads using callable and future
1. Create the implementation class for the callable interface and implement the call () method, which acts as a thread execution body, has a return value, and then creates an instance of the callable implementation class. Starting with JAVA8, you can create callable objects directly using lambda expressions.
2. Use Futuretask 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 Get () method of the Futuretask object to obtain the return value after the completion of the child thread execution.

public class TestCode3 {public static void main (string[] args) {TestCode3 test = NE
        W TestCode3 ();
            futuretask<integer> task = new futuretask<integer> (callable<integer>) ()->{int i=0;
            for (; i<100;i++) {System.out.println (Thread.CurrentThread (). GetName () + "loop variable i value:" +i);
        return i;
        });
            for (int i=0;i<100;i++) {System.out.println (Thread.CurrentThread (). GetName () + "loop variable i value:" +i);
            if (i==20) {New Thread (task, "Thread with return value"). Start ();
            try{System.out.println ("The return value of the child thread:" +task.get ());
            catch (Exception e) {e.printstacktrace (); }
        }
    }
}

Iv. talking about three ways of superiority and disadvantage
     can implement multithreading by inheriting the thread class or implementing runnable, callable interfaces, However, the implementation of the Runnable interface and the implementation of the callable interface is basically the same, but the callable interface defined in the method has a return value, you can declare thrown exception. Therefore, the implementation of runnable interface and implementation of the callable interface can be classified as a way. The main differences between this approach and the inheritance thread approach are as follows.
    1. Advantages and disadvantages of creating multithreading in a way that implements Runnable, callable interfaces:
Advantages: (1) The thread class only implements the Runnable interface and the callable interface. You can also inherit other classes.
            (2) In this way, multiple threads can share a target object, So it is very suitable for multiple threads to handle the same resource, so that the CPU, code and data can be separated to form a clear model, which embodies the object-oriented thought well.
Disadvantage: Programming is slightly complex, and you must use the Thread.CurrentThread () method if you need to access the current thread.
    2. Advantages and disadvantages of creating multithreading using the inherited thread class:
Disadvantage: Because the thread class has inherited the thread class, no other parent class can be inherited.
Advantage: Writing is simple, and if you need to access the current thread, you can get the current thread without using the Thread.CurrentThread () method.
V. Summary
     in view of the above analysis, it is generally recommended to implement Runnable interface, callable interface to create multithreading.

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.