Home > Java > javaTutorial > Introduction to 3 methods of creating threads in Java (code)

Introduction to 3 methods of creating threads in Java (code)

不言
Release: 2019-02-01 11:21:29
forward
2814 people have browsed it

This article brings you an introduction to the three methods (code) of creating threads in Java. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

If you want to create a thread in java, there are generally three methods:

  1. Inherit the Thread class;

  2. implementation Runnable interface;

  3. Use Callable and Future to create threads.

1. Inherit the Thread class

If you inherit the Thread class, you must override the run method and define the tasks that need to be performed in the run method.

class MyThread extends Thread{
    private static int num = 0;
     
    public MyThread(){
        num++;
    }
     
    @Override
    public void run() {
        System.out.println("主动创建的第"+num+"个线程");
    }
}
Copy after login

After creating your own thread class, you can create a thread object, and then start the thread through the start() method. Note that the run() method is not called to start the thread. The run method only defines the tasks that need to be performed. If the run method is called, it is equivalent to executing the run method in the main thread. There is no difference from ordinary method calls. At this time, there is no A new thread will be created to perform the defined tasks.

public class Test {
    public static void main(String[] args)  {
        MyThread thread = new MyThread();
        thread.start();
    }
}
 
 
class MyThread extends Thread{
    private static int num = 0;
     
    public MyThread(){
        num++;
    }
     
    @Override
    public void run() {
        System.out.println("主动创建的第"+num+"个线程");
    }
}
Copy after login

In the above code, by calling the start() method, a new thread will be created. In order to distinguish the difference between start() method call and run() method call, please look at the following example:

public class Test {
    public static void main(String[] args)  {
        System.out.println("主线程ID:"+Thread.currentThread().getId());
        MyThread thread1 = new MyThread("thread1");
        thread1.start();
        MyThread thread2 = new MyThread("thread2");
        thread2.run();
    }
}
 
 
class MyThread extends Thread{
    private String name;
     
    public MyThread(String name){
        this.name = name;
    }
     
    @Override
    public void run() {
        System.out.println("name:"+name+" 子线程ID:"+Thread.currentThread().getId());
    }
}
Copy after login

Run result:

The following conclusions can be drawn from the output results:

1) The thread IDs of thread1 and thread2 are different, and thread2 and the main thread ID are the same, indicating that calling the run method does not create a new thread, but in the main thread Directly running the run method in is no different from ordinary method calls;

2) Although the start method call of thread1 is called before the run method of thread2, the information related to the run method call of thread2 is output first. , indicating that the process of creating a new thread will not block the subsequent execution of the main thread.

2. Implement the Runnable interface

In addition to inheriting the Thread class when creating a thread in Java, you can also implement similar functions by implementing the Runnable interface. Implementing the Runnable interface must override its run method.

The following is an example:

public class Test {
    public static void main(String[] args)  {
        System.out.println("主线程ID:"+Thread.currentThread().getId());
        MyRunnable runnable = new MyRunnable();
        Thread thread = new Thread(runnable);
        thread.start();
    }
}
 
 
class MyRunnable implements Runnable{
     
    public MyRunnable() {
         
    }
     
    @Override
    public void run() {
        System.out.println("子线程ID:"+Thread.currentThread().getId());
    }
}
Copy after login

The Chinese meaning of Runnable is "task". As the name suggests, by implementing the Runnable interface, we define a subtask and then hand over the subtask to Thread for execution. . Note that this method must use Runnable as a parameter of the Thread class, and then use Thread's start method to create a new thread to perform the subtask. If you call Runnable's run method, no new thread will be created. This ordinary method call makes no difference.

In fact, if you look at the implementation source code of the Thread class, you will find that the Thread class implements the Runnable interface.

In Java, these two methods can be used to create threads to perform subtasks. Which method to choose depends on your own needs. Directly inheriting the Thread class may look simpler than implementing the Runnable interface, but since Java only allows single inheritance, if a custom class needs to inherit other classes, it can only choose to implement the Runnable interface.

3. Use Callable and Future to create threads

Unlike the Runnable interface, the Callable interface provides a call() method as the thread execution body, the call() method It is more powerful than the run() method.

The steps to create and start a thread with a return value are as follows:

  1. Create an implementation class of the Callable interface, implement the call() method, and then create an implementation class of the Instance (starting from java8, you can directly use Lambda expressions to create Callable objects).

  2. Use the FutureTask class to wrap the Callable object. The FutureTask object encapsulates the return value of the call() method of the Callable object.

  3. Use the FutureTask object Create and start a thread as the target of the Thread object (because FutureTask implements the Runnable interface)

  4. Call the get() method of the FutureTask object to obtain the return value after the execution of the child thread ends

The following is an example:

public class Main {

  public static void main(String[] args){

   MyThread3 th=new MyThread3();

   //使用Lambda表达式创建Callable对象

     //使用FutureTask类来包装Callable对象

   FutureTask<Integer> future=new FutureTask<Integer>(

    (Callable<Integer>)()->{

      return 5;

    }

    );

   new Thread(task,"有返回值的线程").start();//实质上还是以Callable对象来创建并启动线程

    try{

    System.out.println("子线程的返回值:"+future.get());//get()方法会阻塞,直到子线程执行结束才返回

    }catch(Exception e){

    ex.printStackTrace();

   }

  }

}
Copy after login

Comparison of three ways to create threads:

implementing Runnable and implementing Callable interface The methods are basically the same, except that the latter has a return value when executing the call() method, and the latter has no return value when executing the run() method of the thread execution body. Therefore, these two methods can be classified into one. This method is the same as the method that inherits the Thread class. The differences are as follows:

  1. Threads only implement Runnable or implement the Callable interface, and can also inherit other classes.

  2. In this way, multiple threads can share a target object, which is very suitable for situations where multiple threads process the same resource.

  3. But the programming is slightly complicated. If you need to access the current thread, you must call the Thread.currentThread() method.

  4. A thread class that inherits the Thread class cannot inherit from other parent classes (Java single inheritance decision).

PS: It is generally recommended to create multi-threads by implementing interfaces

The above is the detailed content of Introduction to 3 methods of creating threads in Java (code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template