Three ways to implement multithreading in Java

1. Implement multithreading mode 1: inherit Thread class [application]

  • Method introduction

    Method nameexplain
    void run()After the thread is started, this method will be called and executed
    void start()When this thread starts executing, the Java virtual opportunity calls the run method ()
  • Implementation steps

    • Define a class MyThread to inherit the Thread class

    • Override the run() method in the MyThread class

    • Create an object of the MyThread class

    • Start thread

  • Code demonstration

    public class MyThread extends Thread {
        @Override
        public void run() {
            for(int i=0; i<100; i++) {
                System.out.println(i);
            }
        }
    }
    public class MyThreadDemo {
        public static void main(String[] args) {
            MyThread my1 = new MyThread();
            MyThread my2 = new MyThread();
    
    //        my1.run();
    //        my2.run();
    
            //void start() causes this thread to start execution; The Java virtual machine calls the run method of this thread
            my1.start();
            my2.start();
        }
    }

  • Two small problems

    • Why override the run() method?

      Because run() is used to encapsulate the code executed by the thread

    • What is the difference between the run() method and the start() method?

      run(): encapsulates the code executed by the thread. It is called directly, which is equivalent to the call of ordinary methods

      start(): start the thread; The run() method of this thread is then called by the JVM

 

2. Implement multithreading mode 2: implement Runnable interface [application]

  • Thread construction method

    Method nameexplain
    Thread(Runnable target)Assign a new Thread object
    Thread(Runnable target, String name)Assign a new Thread object
  • Implementation steps

    • Define a class MyRunnable to implement the Runnable interface

    • Override the run() method in the MyRunnable class

    • Create an object of the MyRunnable class

    • Create an object of Thread class and take the MyRunnable object as the parameter of the construction method

    • Start thread

  • Code demonstration

    public class MyRunnable implements Runnable {
        @Override
        public void run() {
            for(int i=0; i<100; i++) {
                System.out.println(Thread.currentThread().getName()+":"+i);
            }
        }
    }
    public class MyRunnableDemo {
        public static void main(String[] args) {
            //Create an object of the MyRunnable class
            MyRunnable my = new MyRunnable();
    ​
            //Create an object of Thread class and take the MyRunnable object as the parameter of the construction method
            //Thread(Runnable target)
    //        Thread t1 = new Thread(my);
    //        Thread t2 = new Thread(my);
            //Thread(Runnable target, String name)
            Thread t1 = new Thread(my,"Tank");
            Thread t2 = new Thread(my,"aircraft");
    ​
            //Start thread
            t1.start();
            t2.start();
        }
    }

3. Implement multithreading mode 3: implement Callable interface [application]

  • Method introduction

    Method nameexplain
    V call()Calculate the result. If the result cannot be calculated, an exception will be thrown
    FutureTask(Callable<V> callable)Create a FutureTask and execute the given Callable once it is run
    V get()If necessary, wait for the calculation to complete, and then obtain its results
  • Implementation steps

    • Define a class MyCallable to implement the Callable interface

    • Override the call() method in the MyCallable class

    • Create an object of the MyCallable class

    • Create the FutureTask object of the implementation class of Future, and take the MyCallable object as the parameter of the construction method

    • Create an object of Thread class and take FutureTask object as the parameter of construction method

    • Start thread

    • Then call the get method to get the result after the thread ends.

  • Code demonstration

    public class MyCallable implements Callable<String> {
        @Override
        public String call() throws Exception {
            for (int i = 0; i < 100; i++) {
                System.out.println("Confess to the girl" + i);
            }
            //The return value represents the result after the thread runs
            return "promise";
        }
    }
    public class Demo {
        public static void main(String[] args) throws Exception {
            //After the thread is started, you need to execute the call method inside
            MyCallable mc = new MyCallable();
    ​
            //Thread t1 = new Thread(mc);
    ​
            //You can get the result after the Thread is executed. You can also pass it to the Thread object as a parameter
            FutureTask<String> ft = new FutureTask<>(mc);
    ​
            //Create thread object
            Thread t1 = new Thread(ft);
    ​
            String s = ft.get();
            //Open thread
            t1.start();
    ​
            //String s = ft.get();
            System.out.println(s);
        }
    }

  • Comparison of three implementation methods

    • Implement Runnable and Callable interfaces

      • Advantages: strong extensibility. You can inherit other classes while implementing this interface

      • Disadvantages: the programming is relatively complex and the methods in the Thread class cannot be used directly

    • Inherit Thread class

      • Benefits: programming is relatively simple. You can directly use the methods in the Thread class

      • Disadvantages: poor extensibility, unable to inherit other classes

 

Keywords: Java JavaSE

Added by fnbcprog on Wed, 22 Sep 2021 17:19:12 +0300