编程知识 cdmana.com

Three ways of creating thread in Java and their comparison are described in detail

One 、Java There are three main ways to create threads in :

1、 Inherit Thread Class to create a thread class

  • Definition Thread Subclasses of classes , And override the run Method , The run The method body of the method represents the task to be completed by the thread . So the run() Methods are called executors .

  • establish Thread Instances of subclasses , The thread object is created .

  • Calling the start() Method to start the thread .

The sample code is :

package com.thread;  

public class FirstThreadTest extends Thread{  
    int i = ;  
    // rewrite run Method ,run The method body of the method is the field execution body   
    public void run()  
    {  
        for(;i<100;i++){  
        System.out.println(getName()+"  "+i);  
        }  
    }  
    public static void main(String[] args)  
    {  
        for(int i = ;i< 100;i++)  
        {  
            System.out.println(Thread.currentThread().getName()+"  : "+i);  
            if(i==20)  
            {  
                new FirstThreadTest().start();  
                new FirstThreadTest().start();  
            }  
        }  
    }  
}

In the above code Thread.currentThread() Method returns the currently executing thread object .GetName() Method returns the name of the thread that called the method .

2、 adopt Runnable Interface create thread class

  • Definition runnable Implementation class of interface , Override the interface run() Method , The run() The method body of the method is also the thread execution body of the thread .

  • establish Runnable Instance of implementation class , And take this example as Thread Of target To create Thread object , The Thread Object is the real thread object .

  • Calling the start() Method to start the thread .

The sample code is :

package com.thread;  

public class RunnableThreadTest implements Runnable  
{  

    private int i;  
    public void run()  
    {  
        for(i = ;i <100;i++)  
        {  
            System.out.println(Thread.currentThread().getName()+" "+i);  
        }  
    }  
    public static void main(String[] args)  
    {  
        for(int i = ;i < 100;i++)  
        {  
            System.out.println(Thread.currentThread().getName()+" "+i);  
            if(i==20)  
            {  
                RunnableThreadTest rtt = new RunnableThreadTest();  
                new Thread(rtt," New Threads 1").start();  
                new Thread(rtt," New Threads 2").start();  
            }  
        }  
    }   
}

The thread execution process is very simple , When executing code start() when , Will execute the overridden in the object void run(); Method , After the method is executed , Threads die .

3、 adopt Callable and Future Create thread

(1) establish Callable Implementation class of interface , And implement call() Method , The call() Method will act as thread body , And there is a return value .

public interface Callable
{
  V call() throws Exception;
}

(2) establish Callable Instance of implementation class , Use FutureTask Class to packaging Callable object , The FutureTask Object encapsulates the Callable Object's call() Return value of method .(FutureTask It's a wrapper , It's by accepting Callable To create , It also realizes Future and Runnable Interface .)

(3) Use FutureTask Object as Thread Object's target Create and start a new thread .

(4) call FutureTask Object's get() Method to get the return value after the execution of the child thread

   The sample code :

package com.thread;  

import java.util.concurrent.Callable;  
import java.util.concurrent.ExecutionException;  
import java.util.concurrent.FutureTask;  

public class CallableThreadTest implements Callable<Integer>  
{  

    public static void main(String[] args)  
    {  
        CallableThreadTest ctt = new CallableThreadTest();  
        FutureTask<Integer> ft = new FutureTask<>(ctt);  
        for(int i = ;i < 100;i++)  
        {  
            System.out.println(Thread.currentThread().getName()+"  Loop variable of i Value "+i);  
            if(i==20)  
            {  
                new Thread(ft," A thread with a return value ").start();  
            }  
        }  
        try  
        {  
            System.out.println(" Return value of the child thread :"+ft.get());  
        } catch (InterruptedException e)  
        {  
            e.printStackTrace();  
        } catch (ExecutionException e)  
        {  
            e.printStackTrace();  
        }  

    }  

    @Override  
    public Integer call() throws Exception  
    {  
        int i = ;  
        for(;i<100;i++)  
        {  
            System.out.println(Thread.currentThread().getName()+" "+i);  
        }  
        return i;  
    }  

}

Two 、 Comparison of three ways to create threads

1、 Implemented using Runnable、Callable When creating a multithreaded interface ,

Advantage is :

The thread class just implements Runnable Interface or Callable Interface , You can also inherit from other classes . In this way , Multiple threads can share the same target object , So it is very suitable for multiple threads to handle the same resource , So that we can put CPU、 Separate code from data , Form a clear model , It better embodies the idea of object-oriented .

The disadvantage is :

Programming is a little more complicated , If you want to access the current thread , Must be used Thread.currentThread() Method .

2、 Using inheritance Thread Class to create a multithreaded ,

Advantage is :

Write simple , If you need to access the current thread , No need to use Thread.currentThread() Method , Use it directly this To get the current thread .

The disadvantage is :

The thread class has inherited Thread class , So you can no longer inherit other parent classes .

3、Runnable and Callable The difference between

(1) Callable Regulations ( rewrite ) Approach is to call(),Runnable Regulations ( rewrite ) Approach is to run().

(2) Callable After the task is executed, it can return the value , and Runnable The task of cannot return a value .

(3) call Methods can throw exceptions ,run Method can not .

(4) function Callable The mission can get a Future object , Represents the result of an asynchronous calculation . It provides a way to check if the calculation is complete , To wait for the calculation to complete , And retrieve the calculated results . adopt Future Object can understand task execution , The execution of the task can be cancelled , You can also get execution results .

PS: If there is anything you don't understand in the process of reading , Or if you have any questions you want to extend your consultation , You can leave a message or contact me directly through the bulletin board to help you answer ! And some of the things I've been working on these days Java Learning manual , Interview questions , development tool ,PDF Document book tutorial , If you need it, you can share it for free .

版权声明
本文为[Mo de emotional code Nong]所创,转载请带上原文链接,感谢

Scroll to Top