The Java multi-threaded (2)

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/qq_36209121/article/details/77101313

Foreword

We have already introduced two ways to achieve multi-threaded multi-threaded (1) Java in , now and then summarize the first three kinds of implementations.

When the return value is the time we need to get the thread can use the following ways.


Second, to get the return value of multi-threaded

If you want to get the return value of the thread processing need to use Callable interface to manage the use ExecutorService, the return value from the Future object to handle.

  • Create a task class that implements the Callable interface rewrite run method;
  • Create a thread pool, access to ExecutorService objects;
  • We created the thread object passed to the submit method as a parameter;
  • Future object to obtain a return value;

code show as below

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ThreadMain02 {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        try {
            for(int i=0;i<5;i++) {
                Future<String> future = executorService.submit(new ThreadCallable01());
                System.out.println(future.get().toString());
            }
        }catch(Exception e) {
            e.printStackTrace();
        }finally {
            executorService.shutdown();
        }
    }
}

class ThreadCallable01 implements Callable<String> {
    private Integer total;

    @Override
    public String call() throws Exception {
        return Thread.currentThread().getName()+" -- is running";
    }
}

Gets the return value of the thread

When we get the return value of the thread, you can create yourself a Future of the list to hold the return values ​​of the set, but when there is a thread did not get the return value will produce blocked thread, leading to the completion of the back of the task can not be obtained in a timely manner As a result, until the thread returns the result to get the position.


To address this situation, use can be obtained ExecutorCompletionService result set is eligible;
run the following code:

package com.test;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadMain03 {

    public static void main(String[] args) {
        int threads = 10;
        ExecutorService es = Executors.newFixedThreadPool(threads);
        ExecutorCompletionService<String> completionService = new ExecutorCompletionService<String>(es);
        try {
            for(int i=0;i<5;i++) {
                completionService.submit(new TaskCallable03((threads-i),i));
            }

            for(int i=0;i<5;i++) {
                System.out.println("i="+i+" -- "+completionService.take().get());
            }
        }catch(Exception e) {
            e.printStackTrace();
        }finally {
            es.shutdown();
        }
    }
}

class TaskCallable03 implements Callable<String> {
    private int time;
    private int num;

    public TaskCallable03(int time, int num) {
        this.time=time;
        this.num = num;
    }

    @Override
    public String call() throws Exception {
        Thread.sleep(time);
        return Thread.currentThread().getName()+" -- is running" + " -- num="+num;
    }
}

Return result

i=0 -- pool-1-thread-1 -- is running -- num=0
i=1 -- pool-1-thread-5 -- is running -- num=4
i=2 -- pool-1-thread-4 -- is running -- num=3
i=3 -- pool-1-thread-3 -- is running -- num=2
i=4 -- pool-1-thread-2 -- is running -- num=1

From the above operating results, and ExecutorCompletionService binding code:
ExecutorCompletionService BlockingQueue in a queue, the queue is implemented LinkedBlockingQueue linked list structure,
the first finished executing, the first object into ExecutorCompletionService result set, thus avoiding the foregoing structure does not perform blocking effect caused complete.


参考了许多大牛的博客, 如有不当地方, 欢迎告知, 谢谢.

Guess you like

Origin blog.csdn.net/qq_36209121/article/details/77101313