Home > Java > JavaBase > body text

Several ways to implement multithreading in java

王林
Release: 2019-12-04 16:43:08
Original
4879 people have browsed it

Several ways to implement multithreading in java

There are three ways to use Java multi-threading: inherit the Thread class, implement the Runnable interface and use Callable and Future to create threads.

1. Inherit the Thread class

The implementation is very simple. You only need to create a class to inherit the Thread class and then override the run method. Multi-thread concurrency can be achieved by calling the start method of the instance object of this class in the main method. Code:

public class MyThread extends Thread {
    @Override
    public void run(){        
        super.run();
        System.out.println("执行子线程...");
    }
}
Copy after login

Test case:

public class Test {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
        System.out.println("主线程...");
    }
}
Copy after login

Running result:

Several ways to implement multithreading in java

Of course, the results here do not represent the execution order of the threads. It is executed concurrently. If it is run several times, the printing order may be different. During multi-threaded running, the CPU executes threads in an uncertain manner, so the running results have nothing to do with the execution order of the code or the calling order, and the running results may also be different.

Free video tutorial recommendation: java learning video

Another point to note here is that the start method of myThread should be called in the main method, not run ()method. Calling the start() method tells the CPU that this thread is ready for execution, and the system will execute its run() method when it has time.

When calling the run() method directly, it is not executed asynchronously, but executed synchronously in sequence like calling a function, which loses the meaning of multi-threading.

2. Implement the Runnable interface

#The implementation of this method is also very simple, that is, to inherit the Thread class and implement the Runnable interface. The code is as follows:

public class MyRunnable implements Runnable {    
    @Override
    public void run() {
        System.out.println("执行子线程...");
    }
}
Copy after login

Test case:

public class Test {    
    public static void main(String[] args) {
        Runnable runnable = new MyRunnable();
        Thread thread = new Thread(runnable);
        thread.start();
        System.out.println("主线程运行结束!");
    }
}
Copy after login

Running result:

Several ways to implement multithreading in java

There is nothing to say about the running result, you can see it in main here When it comes to actually creating a new thread, it is still created through Thread:

Thread thread = new Thread(runnable);
Copy after login

The function of the Thread class in this step is to package the run() method into a thread execution body, and then still use start to tell the system that the thread is ready to be scheduled. implement.

3. Use Callable and Future to create threads

The above two methods have these two problems:

1. The return value of the child thread cannot be obtained;

2. The run method cannot throw an exception.

In order to solve these two problems, we need to use the Callable interface. Speaking of interfaces, the above Runnable interface implementation class instance is passed in as a parameter of the constructor of the Thread class, and then the content in the run method is executed through Thread's start. However, Callable is not a sub-interface of Runnable, but a brand new interface. Its instance cannot be directly passed into the Thread construct, so another interface is needed to convert it.

Java5 provides the Future interface to represent the return value of the call() method in the Callable interface, and provides an implementation class FutureTask for the Future interface. The inheritance relationship of the implementation class is as shown in the figure:

Several ways to implement multithreading in java

As you can see, this implementation class not only implements the Future interface, but also implements the Runnable interface, so it can be passed directly to the Thread constructor.

The constructor of FutureTask is as follows:

So there is actually one more conversion process than the previous method. In the end, a new thread is created through Thread's start. With this idea, the code is easy to understand:

import java.util.concurrent.Callable;
public class MyCallable implements Callable {    
int i = 0;    
@Override
    public Object call() throws Exception {
        System.out.println(Thread.currentThread().getName()+"  i的值:"+ i);        
        return i++; //call方法可以有返回值
    }
}
Copy after login

Test:

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class Test {
    public static void main(String[] args) {
        Callable callable = new MyCallable();        
        for (int i = 0; i < 10; i++) {
            FutureTask task = new FutureTask(callable);            
            new Thread(task,"子线程"+ i).start();            
            try {                //获取子线程的返回值
                System.out.println("子线程返回值:"+task.get() + "\n");
            }  catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
Copy after login

Execution result (part):

Several ways to implement multithreading in java

##Related Recommended article tutorials:

java introductory program

The above is the detailed content of Several ways to implement multithreading in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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