Creation of java multithreading

Method 1: Inherit the Thread class

Java represents threads through the java.lang.Thread class

1. Define a MyThread that inherits the thread class java.lang.Thread and rerun() method

2. Create a MyThread object.

4. Call the start() method of the thread object to start the thread (the run method is still executed after startup)

package com.Thread.create;

public class MyThreadDemo1 {
    public static void main(String[] args) {
        //New object calls the start method to start executing the thread
        new Mythread().start();


        for (int i = 0; i < 500; i + + ) {
            System.out.println("main thread");
        }
    }
}



//1. Define a thread class that inherits Thread
class Mythread extends Thread{
//2. Rewrite the run method
    @Override
    public void run() {
        for (int i = 0; i <500; i + + ) {
            System.out.println("Thread output" + i);
        }
    }
}

Advantages and disadvantages:

Advantages: simple coding

Disadvantages: The thread class has inherited Thread and cannot inherit other classes, which is not conducive to expansion.

Usage Note:

Why not call the run method directly, but call start to start the thread.

Directly calling the run method will be executed as a normal method, which is equivalent to a single thread.

Only calling the start method starts a new thread.

Do not place main thread tasks before child threads:

Because this will also be executed as a single thread.

Method 2: Implement Runable interface

1. Define a thread task MyRunable to implement the Runable interface and override the run() method

2. Create a MyRunable task object

3. Hand the MyRunable task object to Thread for processing

4. Call the start() method of the thread object to start the thread

package com.Runable.create;




/*
       Objective: Thread creation method 2, understand its advantages and disadvantages
 */
public class ThreadDemo2 {
    public static void main(String[] args) {
        //3Create task object
        Runnable target = new MyRunnable();
        //4 Hand the thread object to Thread for processing and start start
        new Thread(target).start();
        for (int i = 0; i < 500; i + + ) {
            System.out.println("I am ======================================" );
        }

    }
}
/*
    1Define a thread task class and implement the runable interface
 */
class MyRunnable implements Runnable{

    /*
        2 Rewrite the run method and define thread tasks
     */

    @Override
    public void run() {
        for (int i = 0; i < 500; i + + ) {
            System.out.println("Sub-thread task" + i);
        }
    }
}

Advantages and disadvantages:

Advantages: The thread task class only implements the interface, and can continue to inherit classes and implement interfaces, and has strong scalability.

Disadvantages: Programming requires an extra layer of object packaging. If the thread has execution results, it cannot be returned directly.

Implement Runable interface (anonymous inner class)

1. Create a Runable anonymous inner class object

2. Leave it to Thread for processing.

3. Call start() of the thread object to start the thread.

package com.Runable.create;




/*
       Objective: Thread creation method 2, understand its advantages and disadvantages
 */
public class ThreadDemo3 {
    public static void main(String[] args) {

        //Form of anonymous inner class
        Runnable target = new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 50; i + + ) {
                    System.out.println("I am child thread 1*");
                }

            }
        };
        new Thread(target).start();

        //main thread
        for (int i = 0; i < 50; i + + ) {
            System.out.println("I am the main thread");
        }

        //The second form of anonymous inner class.
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 50; i + + ) {
                    System.out.println("I am child thread 2*");
                }
            }
        }).start();


    }
}
/*

 */

Method 3: Implement the Callable interface

Implemented using callable and FutureTask interfaces

1. Get the task object

1. Define a class to implement the Callable interface, override the call method, and encapsulate what needs to be done.

2. Use FutureTask to encapsulate the Callable object into a thread task object.

2. Hand over thread tasks to Thread for processing

3. Call the start method of Thread to start the thread and perform the task.

4. After the thread execution is completed, obtain the execution result through the get method of FutureTask

package com.Runable.create;


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

/*
    Implement the callable interface and complete it for FutureTask
 */
public class ThreadDemo4 {
    public static void main(String[] args) {
        /*
            3.Create task object

         */
        Callable<String> call = new MyCallable(100);
        /*
            4. Hand the callable task object to the Futuretast object
            Function 1 of the FutureTask object: It is a Runable object (implements the Runnable interface) and can be handed over to Thread
            Function 2 of the FutureTask object: You can get the execution result of the thread through its get method after the thread execution is completed.

         */

        FutureTask<String> f1 = new FutureTask<String>(call);

        /*
            5. Leave it to the thread for processing
         */

        new Thread(f1).start();




        Callable<String> call1 = new MyCallable(100);
        FutureTask<String> f2 = new FutureTask<String>(call1);
        new Thread(f2).start();


        try {
            String rs1= f1.get();
            System.out.println("First result:" + rs1);
        } catch (Exception e) {

        }


        try {
            String rs2= f2.get();
            System.out.println("Second result:" + rs2);
        } catch (Exception e) {

        }

    }
}


/*
    1. Define task classes. Implementing the Callable interface should declare the result data type after the thread task is executed.
 */

class MyCallable implements Callable<String>{
    private int n;

    public MyCallable(int n) {
        this.n = n;
    }
    /*
        2. Rewrite the call method (the thread’s task method)
     */

    @Override
    public String call() throws Exception {
        int sum = 0;
        for (int i = 0; i <=n; i + + ) {
            sum + =i;

        }
        return "The result of the sub-thread execution is: " + sum;
    }
}

Advantages and Disadvantages:

Advantages: Thread tasks only implement interfaces, and can continue to inherit classes and implement interfaces, which is highly scalable.

You can obtain the execution result of the thread after the thread execution is completed.

shortcoming:

Coding is a little more complicated.

Comparison of three methods: