Java Concurrent Programming (2) Three Methods of Creating Threads

process and thread

  1. 1.  Process

The relationship between the process and the code is like the relationship between the music and the score. When the performance ends, the music is gone but the score is still there; when the program execution ends, the process disappears but the code is still there, and the computer is the code. 's player.

2. Thread

A thread can be likened to the sound of a certain musical instrument in the process of playing. There can be few kinds of musical instrument sounds, but not all of them—a process contains at least one thread. Threads are at the heart of program execution, just as there is no music without the sound of a specific instrument.

Three ways to create a thread

1. Inherit the Thread method

     1). Define the thread class

When inheriting the Thread method, you need to override the run() method of Thread. The code in the run() method is the code you want to execute concurrently.

class ExampleThread extends Thread {
   @Override
    public void run() {
        doSomething();
    }
}    

2). Execute the code of the thread class

Create an ExampleThread object in the main() method, call the start() method of the object, and the start() method will create a corresponding thread through a series of operations on the bottom layer of the system, and execute concurrently with the current thread. If the run() method is called directly, the program will execute the code behind the main() method after executing the run() method, which is a single-threaded execution instead of multi-threaded concurrent execution.

public class CreateThread {
    public static void main(String[] args) {
        ExampleThread thread = new ExampleThread();
        thread.start();//Note that it is start(), not run()
        //The following code can be executed concurrently with the code in the run() method
        doSomethingElse();
   }
}        

  

2. Implement the Runnable interface

1). Define the thread class

Using the Runnable interface is similar to inheriting the Thread class. The run() method is also written in the new class. The content of the method is the code to be executed by the new thread.

class ExampleThread implements Runnable	{
  @Override
  public void run() {
    doSomething();
  }
}

2). Execute the code of the thread class

   There is no start() method in a class that implements the Runnable interface, so we should "find a" start() method for this thread. The Thread class has a constructor with Runnable parameters. We pass the ExampleThread object as a parameter to the Thread constructor, and then call the start() method of the Thread object to generate a thread. Is there a kind of "borrowing"? The chicken-and-egg feeling.

public class CreateThread {
  public static void main(String[] args) {
    Runnable runnable = new ExampleThread()
    Thread thread = new Thread(runnable);
    thread.start();//Note that it is start(), not run()
    //The following code can be executed concurrently with the code in the run() method
    doSomethingElse();
  }
}

3. Implement the Callable interface

1). Define the thread class    

The above-mentioned methods of using Thread and Runnable to implement multi-threading cannot get the return value from the previous thread, but sometimes when a thread finishes running, you want it to return some valuable information, such as whether certain operations are performed. It worked. The Callable interface is used to solve such problems. The Callable interface is an interface with a generic type, and the type of the generic type is the type of the return value of the thread. Implement the call() method in the Callable interface. The return type of the method is the same as the generic type.

class ExampleThread implements Callable<String>	{
  @Override
  public String call() {
    doSomething();
    return "Some Value";
  }
}

2). Execute the code of the thread class

The method of executing this thread class is similar to Runnable, but Callable needs to wrap a layer of FutureTask before calling the start() method. FutureTask is used to obtain the value returned by the thread. The specific code is as follows:

public class CreateThread {
  public static void main(String[] args) {
    Callable<String> callable = new ExampleThread();
    FutureTask<String> task = new FutureTask<String>(callable);
    Thread thread = new Thread(task);
    thread.start();//Note that it is start(), not call()
    doSomethingElse();
    try {
      String returnVal = task.get();//The return value of the thread is obtained here
    } catch (InterruptedException e) {
      e.printStackTrace ();
    } catch (ExecutionException e) {
      e.printStackTrace ();
    }
  }
}

  

 

There is a point to note here. When calling task.get(), the newly created thread may not have finished executing. At this time, the current thread that calls the get() method will be blocked until the execution of the newly created thread ends. Therefore, the task.get() code is best called when the current thread has to use the return value, so that the current thread can continue to execute code unrelated to the return value.

Summarize

Threads generated by inheriting the Thread class and implementing the Runnable interface have no return value. Threads that implement the Callable interface can have a return value, but be careful not to block the current thread prematurely.

Inheriting the Thread class and implementing the Runnable interface have their own advantages. Inheriting the Thread class can easily use the start() method to start the thread, but it also brings a drawback: inheritance makes the new class and the Thread class strongly coupled, in addition , Since Java does not support multiple inheritance, new classes cannot inherit from other classes. Implementing the Runnable interface is the opposite.

So the question is, how to choose Thread and Runnable? My suggestion is to use Runnable as much as possible. Some people may say: Use Runnable or call the start() method of Thread, it is better to use Thread directly. Hey, in fact, the thread pool can replace the start() of Thread, predict the details, and see the breakdown below. Public number: Talk about the code today. Follow my official account to view serialized articles. If you have any questions that you don't understand, just leave a message on the official account.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325246328&siteId=291194637