How to implement Java multithreading

The JVM allows applications to execute concurrently. There are generally three ways to achieve multithreading:

1. Inherit the Thread class and rewrite the run() method Thread is essentially an instance of the Runnable interface, which represents an instance of a thread, and the only way to start a thread is through the start() method of the Thread class, start() The method is a local method. It will start a new thread and execute the run() method. By directly inheriting the Thread class and overriding the run() method, you can start a new thread and execute your own defined run() method. However, after calling the start() method, the multi-threaded code is not executed immediately, but the changed thread becomes a runnable state. When to run the multi-threaded code is determined by the operating system.

example:

class MyThread1 extends Thread{ //Create thread class 1

    public void run(){

        System.out.println("Thread 1"); 

    }

}

class MyThread2 extends Thread{ //Create thread class 2

    public void run(){

        System.out.println("Thread 2"); 

    }

}

public class Test{

    public static void main(String []args){

        MyThread1 myThread1=new MyThread1();

        MyThread2 myThread2=new MyThread2();

        myThread1.start(); //Start thread 1

        myThread2.start(); //Start thread 2

    }

}

2. Implement the Runnable interface and implement the run() method

step:

1) Define a class, implement the Runnable interface, and implement the run() method in it

2) Create a Thread object and instantiate the Thread object with the object that implements the Runnable interface as a parameter;

3) Call the start() method of Thread

class MyThread implements Runnaable{

  public void run(){

    System.out.println("Thread body");

  }

}

public class Test{

  public static void main(String args[]){

    MyThread thread=new MyThread();

    Thread t=new Thread(thread);

    t.start();//Open the thread Finally, the thread is controlled through the API of the Thread object

  }

}

3. Implement the Callable interface and override the call() method

The Callable interface is similar in function to the Runnable interface, but provides more powerful functions than the Runnable interface.

1) The Callable interface provides a return value after the end of the task, and Runnable cannot provide this function;

2) The call() method in Callable can throw exceptions, while the run() method of Runnable cannot throw exceptions;

3) Running Callable can get a Future object. The Future object represents the result of asynchronous calculation. It provides a method to check whether the object is implemented. Since the thread belongs to the asynchronous calculation model, the return value cannot be obtained from other threads. In this case Next, you can use Future to monitor when the target thread calls the call() method. When the get() method of Future is called to get the result, the current thread will block until the call() method ends and returns the result.

public class CallableAndFunture{

  public static class CallableTest implements Callable<String>{

    public String call() throws Exception{

      return "Hello World";

    }

  }

  public static void main(String args[]){

    ExecutorService threadPool = Executor.newSingleThreadExecutor();

    // start the thread

    Funture<String> funture=threadPool.submit(new CallableTest());

    try{

      System.out.println("Waitting thread to finish");

      System.out.println(future.get());//Wait for the thread to end and get the return result

    }caych(Exception e){

      e.printStackTrace ();

    }

  }

}

It is recommended to use the Runnable interface, because the Thread class inherits a variety of methods that can be used or overridden by derived classes, but only the run() method must be overridden. It is implemented in the run() method and the main function of this thread is , We generally believe that a class will be inherited only when taeny needs to be strengthened or self-modified. If it is not necessary to rewrite other methods in the Thread class, the effect of inheriting the Thread class and implementing the Runnable interface is the same, so It is best to implement multithreading by implementing the Runnable interface.

Note: The system starts a thread by calling the start() method of the thread class. At this time, the thread is in a ready state instead of a running state and can be scheduled and executed by the JVM at any time. During the scheduling process, the JVM calls the run() of the thread class. method to complete the actual operation, when the run() method ends, the thread will terminate. The start() method can call the run() method asynchronously, but calling the run() method directly is synchronous, and calling the run() method directly cannot achieve the purpose of multithreading.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326574127&siteId=291194637