编程知识 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.........

版权声明
本文为[Irving the procedural ape]所创,转载请带上原文链接,感谢

Scroll to Top