Four ways java creates threads

Posted by wmac on Sun, 07 Jul 2019 18:05:46 +0200

From: http://blog.csdn.net/win7system/article/details/52807277


http://blog.csdn.net/win7system/article/details/52807277

1. Inherit Thread class + override run() method
Start: Create subclass object + object.start()
Disadvantages: Java Only single inheritance is supported, and if our class has inherited from one class, we can no longer inherit the Thread class.

    /**  
     * Simulate tortoise-rabbit race  
     * 1,Create multithreads (mode one): inherit Thread +override run method (thread body)  
     * 2,Use Threads: Create Subclass Object + Object.start() Method Thread Start  
     */  
       
    public class Demo01 {  
       
        public static void main(String[] args) {  
            //Create Subclass Object  
            Rabbit rab = new Rabbit();  
            Tortoise tor = new Tortoise();    
            //Call the start method to start the thread.Internal controlled by CPU  
            rab.start(); //Do not call the run method; call it internally.  
            tor.start();          
            for(int i=0;i<30;i++)  
            {  
                System.out.println("main-->"+i);                  
            }  
        }  
    }  
       
    class Rabbit extends Thread{  
        //Thread body starts with run  
        @Override  
        public void run() {  
            //Thread Body  
            for(int i=0;i<30;i++)  
            {  
                    System.out.println("The rabbit has run away"+i+"step");                 
            }  
        }  
       
    }  
       
    class Tortoise extends Thread  
    {  
        @Override  
        public void run() {  
            //Thread Body  
            for(int i=0;i<30;i++)  
            {  
                    System.out.println("The tortoise has run away"+i+"step");                 
            }  
        }  
    }  

2. Implement Runnable Interface + Rewrite run Method (Common)
Start: Use static proxy
1) Create real roles
2) Create proxy roles
3) Call the start() method to start the thread
Benefits: Inheritance can be achieved at the same time, and the Runnable interface is more versatile.
1. Avoid Limitations of Single Inheritance
2. Easy sharing of resources
Multithreading is achieved by implementing the Runnable interface.(Static agent design mode used)

    /**  
     * Runnable is recommended for creating threads  
     * 1,Avoid Limitations of Single Inheritance  
     * 2,Easy resource sharing  
     */  
    public class Demo03 {  
        public static void main(String[] args) {  
            //1) Create real roles  
            Programmer pro = new Programmer();  
            //2) Create proxy role + real role reference  
            Thread proxy = new Thread(pro);               
            //3) Call the start() method to start the thread  
            proxy.start();  
       
            for(int i=0;i<100;i++){  
                System.out.println("Chatting QQ");  
            }  
        }  
    }  
       
    /**  
     * Create a process using Runnable  
     * 1,Class implements Runable interface + override run() method  
     * 2,Start multithreading using static proxy  
     *      1),Create Real Roles  
     *      2),Create proxy role  
     *      3),Invoke the start() method to start the thread  
     */  
    class Programmer implements Runnable{  
        @Override  
        public void run() {  
            for(int i=0;i<100;i++){  
                System.out.println("Knock code while you're doing it");  
            }  
        }  
    }  

    /**  
     * Ticket grabbing system  
     * Easy resource sharing  
     */  
    public class Demo04 implements Runnable{  
        private int num = 50;  
        @Override  
        public void run() {  
            while(true){  
                if(num<=0)  
                {  
                    break;//Break  
                }  
                System.out.println(Thread.currentThread().getName()+"Captured last"+num--+"Zhang.");             
            }  
        }  
       
        public static void main(String[] args) {  
            //Real Role  
            Demo04 web = new Demo04();  
            //agent  
            Thread t1 = new Thread(web,"Demasia");  
            Thread t2 = new Thread(web,"Catalina");  
            Thread t3 = new Thread(web,"Head of Debon");  
       
            //Start Thread  
            t1.start();  
            t2.start();  
            t3.start();  
        }  
    }  

3. Create multithreads using the Callable interface
Callable and Future interfaces (since jdk1.5)
Callable is a Runnable-like interface. Classes that implement the Callable interface and classes that implement the Runnable are tasks that can be executed by other threads.
Advantage: You can return a value and throw an exception.
Disadvantages: cumbersome implementation.

    import java.util.concurrent.Callable;  
    import java.util.concurrent.ExecutionException;  
    import java.util.concurrent.ExecutorService;  
    import java.util.concurrent.Executors;  
    import java.util.concurrent.Future;  
       
    /**  
     * Creating multithreads using the Callable interface   
     */  
    public class Demo05 {  
        public static void main(String[] args) throws InterruptedException, ExecutionException {  
            //1. Create Threads  
            ExecutorService ser = Executors.newFixedThreadPool(2);//Open two threads  
       
            Race tortoise = new Race("Old Turtle",1000);  
            Race rabbit = new Race("Rabbit",500);  
       
            //2. Get Future Objects  
            Future<integer> result1 = ser.submit(tortoise);  
            Future<integer> result2 = ser.submit(rabbit);  
       
            Thread.sleep(2000);//2 seconds  
            tortoise.setFlag(false);//Stop the thread body loop setting flag = false;  
            rabbit.setFlag(false);  
            //3. Getting Values  
            int num1 = result1.get();  
            int num2 = result2.get();  
       
            System.out.println("The tortoise has run away-->"+num1+"step");  
            System.out.println("The rabbit has run away-->"+num2+"step");  
            //4. Stop Services  
            ser.shutdownNow();  
        }  
    }  
       
    class Race implements Callable<integer>  
    {  
        private String name;//Name  
        private long time;//Delay Time  
        private boolean flag = true;  
        private int step = 0;//step  
       
        public Race() {  
        }     
        public Race(String name) {  
            super();  
            this.name = name;  
        }  
        public Race(String name, int time) {  
            super();  
            this.name = name;  
            this.time = time;  
        }  
       
        //Return value available  
        @Override  
        public Integer call() throws Exception {  
            while(flag){  
                Thread.sleep(time);//delayed  
                step++;  
            }  
            return step;  
        }  
       
        public String getName() {  
            return name;  
        }  
        public void setName(String name) {  
            this.name = name;  
        }  
        public long getTime() {  
            return time;  
        }  
        public void setTime(long  time) {  
            this.time = time;  
        }  
        public boolean isFlag() {  
            return flag;  
        }  
        public void setFlag(boolean flag) {  
            this.flag = flag;  
        }  
        public int getStep() {  
            return step;  
        }  
        public void setStep(int step) {  
            this.step = step;  
        }  
    }  


4. Applications can use the Executor framework to create thread pools

    import Java.util.concurrent.ExecutorService;  
    import java.util.concurrent.Executors;  
      
    public class ThreadPool {  
        private  static int POOL_NUM = 10;  
        public static void main(String[] agrs){  
            ExecutorService executorService = Executors.newFixedThreadPool(5);  
            for (int i = 0; i < POOL_NUM; i++) {  
                RunnableThread thread = new RunnableThread();  
                executorService.execute(thread);  
            }  
        }  
    }  
    class RunnableThread implements  Runnable{  
        private   int THREAD_NUM = 10;  
        public void run() {  
            for (int i = 0; i <THREAD_NUM; i++) {  
                System.out.println("thread"+Thread.currentThread()+i);  
            }  
              
        }  
    }  


Comparison of several ways:
There are several differences between Callable and Runnable:
(1) Callable specifies call(), while Runnable specifies run().
(2) Callable's task returns a value after execution, while Runnable's task does not.
(3) The call() method can throw an exception, while the run() method cannot throw an exception.
(4) Run the Callable task to get a Future object, which represents the result of an asynchronous calculation.It provides a way to check if the calculation is complete, wait for the calculation to complete, and retrieve the results of the calculation.The Future object lets you know how a task is performing, cancels its execution, and gets the results of its execution.

Implementing the Runnable interface has unparalleled advantages over extending the Thread class.This approach not only facilitates the robustness of the program, enabling code to be shared by multiple threads, but also makes code and data resources relatively independent, making it particularly suitable for multiple threads with the same code to handle the same resource.In this way, threads, code and data resources are effectively separated, which well reflects the idea of object-oriented programming.Therefore, almost all multithreaded programs are implemented by implementing the Runnable interface.

Topics: Java Programming