Home > Java > javaTutorial > body text

How to create and run threads in Java?

王林
Release: 2023-04-19 14:16:05
forward
1601 people have browsed it

    1. Five ways to create and run threads

    The first one: Inherit the Thread class

    This method is the most basic Friends who have studied Java all know this method, so I won’t go into details. It should be noted that: The override implementation uses the run method, and the running thread uses the start method.

    public class FirstWay extends Thread  {
        @Override
        public void run() {
            System.out.println("第一种实现线程的方式:继承Thread类");
        }
        //模拟测试
        public static void main(String[] args) {
            new FirstWay().start();
        }
    }
    Copy after login

    Second: Implement the Runnable interface

    The second implementation method is still very basic. It inherits the Runnable interface and rewrites the run method to implement thread running logic. Note: The running thread requires a layer of new Thread.

    public class SecondWay implements Runnable{
        @Override
        public void run() {
            System.out.println("第二种实现线程的方式:实现Runnable接口");
        }
        //模拟测试
        public static void main(String[] args) {
            new Thread(new SecondWay()).start();
        }
    }
    Copy after login

    The third way: implement the Callable interface

    The third way is to implement the Callable interface. Both the Callable interface and the Runable interface can implement threads.

    public class ThirdWay implements Callable<String> {
        @Override
        public String call() throws Exception {
            System.out.println("第三种实现线程的方式:实现Callable接口");
            return "Callable接口带返回值,可以抛出异常";
        }
    
        //模拟测试
        public static void main(String[] args) throws ExecutionException, InterruptedException {
            FutureTask<String> futureTask = new FutureTask<>(new ThirdWay());
            new Thread(futureTask).start();
            //阻塞方法,获取call方法返回值
            System.out.println(futureTask.get());  //打印:Callable接口带返回值,可以抛出异常
        }
    }
    Copy after login

    The difference is as follows:

    • #The thread method implemented by the Callable interface is call, and the thread method implemented by the Runable interface is run

    • Callable has a return value, Runable interface cannot have a return value

    • Callable interface method call return value can be set to a generic type, the String data type is used in the following example

    • Callable interface method call method can throw exceptions, Runable interface run method cannot throw exceptions

    • Callable interface method through new Thread(futureTask ).start()Run, the get method of FutureTask can obtain the return value of the Callable interface method call method

    • If the Callable interface method call method is abnormal, call the get method of FutureTask The same exception will be thrown when

    Fourth: Thread pool execute

    Starting from JDK5 version, java provides thread pool support by default. Use thread pool Running threads in this way can avoid application downtime caused by infinite expansion of threads, and also saves the resource and time costs of frequent thread creation and destruction.

    public class FourthWay implements Runnable{
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() +
                    ":实现线程的方式Runnable接口,但运行方式不一样,使用线程池");
        }
    
        public static void main(String[] args) {
            //创建一个固定大小的线程池
            ExecutorService threadPool = Executors.newFixedThreadPool(5);
            for(int i = 0;i < 10;i++){
                threadPool.execute(new FourthWay());
            }
        }
    }
    Copy after login

    The thread pool ExecutorService uses the execute method to run the thread implementation of the run method of the Runnable interface. The common feature of the execute method and the run method is that there is no return value.

    pool-1-thread-5:实现线程的方式Runnable接口,但运行方式不一样,使用线程池
    pool-1-thread-2:实现线程的方式Runnable接口,但运行方式不一样,使用线程池
    pool-1-thread-4:实现线程的方式Runnable接口,但运行方式不一样,使用线程池
    pool-1-thread-4:实现线程的方式Runnable接口,但运行方式不一样,使用线程池
    pool-1-thread-4:实现线程的方式Runnable接口,但运行方式不一样,使用线程池
    pool-1-thread-1:实现线程的方式Runnable接口,但运行方式不一样,使用线程池
    pool-1-thread-4:实现线程的方式Runnable接口,但运行方式不一样,使用线程池
    pool-1-thread-3:实现线程的方式Runnable接口,但运行方式不一样,使用线程池
    pool-1-thread-2:实现线程的方式Runnable接口,但运行方式不一样,使用线程池
    pool-1-thread-5:实现线程的方式Runnable接口,但运行方式不一样,使用线程池
    Copy after login

    As can be seen from the above results, the thread pool contains five threads. After the thread is completed, it is not destroyed, but returned to the thread pool. The thread resources are obtained from the thread pool and run again during the next execution.

    Fifth type: thread pool submit

    The following example thread pool ExecutorService uses the submit method to run the thread implementation of the call method of the Callable interface. The common feature of the submit method and the call method is that there return value.

    • The return value of the Callable interface call method can be defined by generics

    • The return value of the ExecutorService thread pool submit method is Future

    The get method of Future can obtain the return value of the call method. At the same time, If the call method throws an exception, the get method of Future will also throw an exception.

    public class FifthWay implements Callable<String> {
        @Override
        public String call() throws Exception {
            return Thread.currentThread().getName() + ":Callable接口带返回值,可以抛出异常";
        }
    
        //模拟测试
        public static void main(String[] args) throws ExecutionException, InterruptedException {
            //保存多线程执行结果
            List<String> retList = new ArrayList<>();
            //创建一个固定大小的线程池
            ExecutorService threadPool = Executors.newFixedThreadPool(5);
            for(int i = 0;i < 10;i++){
                Future<String> future = threadPool.submit(new FifthWay());
                retList.add(future.get());
            }
            //java8 语法,打印retlist
            retList.forEach(System.out::println);
        }
    }
    Copy after login

    There is a small syntax sugar in the above code, retList.forEach(System.out::println);is the method reference provided by java8

    pool-1-thread-1:Callable接口带返回值,可以抛出异常
    pool-1-thread-2:Callable接口带返回值,可以抛出异常
    pool-1-thread-3:Callable接口带返回值,可以抛出异常
    pool-1-thread-4:Callable接口带返回值,可以抛出异常
    pool-1-thread-5:Callable接口带返回值,可以抛出异常
    pool-1-thread-1:Callable接口带返回值,可以抛出异常
    pool-1-thread-2:Callable接口带返回值,可以抛出异常
    pool-1-thread-3:Callable接口带返回值,可以抛出异常
    pool-1-thread-4:Callable接口带返回值,可以抛出异常
    pool-1-thread-5:Callable接口带返回值,可以抛出异常
    Copy after login

    The above is the detailed content of How to create and run threads in Java?. For more information, please follow other related articles on the PHP Chinese website!

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