java high concurrency Series - Day 31: Get the thread execution result, these 6 ways you know?

This is the java series of 31 high concurrency.

Environment: jdk1.8.

java series of high concurrency has learned a lot, and this article, we use the knowledge learned earlier to implement a demand:

Need to get the results of other threads in a thread, you can think of several ways? What advantages and disadvantages?

Combined with this requirement, we use 6 Ways to do a review of previously learned knowledge, enhance memory.

Mode 1: Thread the join () method implementation

Code:

package com.itsoku.chat31;

import java.sql.Time;
import java.util.concurrent.*;

/**
 * 跟着阿里p7学并发,微信公众号:javacode2018
 */
public class Demo1 {
    //用于封装结果
    static class Result<T> {
        T result;

        public T getResult() {
            return result;
        }

        public void setResult(T result) {
            this.result = result;
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println(System.currentTimeMillis());
        //用于存放子线程执行的结果
        Result<Integer> result = new Result<>();
        //创建一个子线程
        Thread thread = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
                result.setResult(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread.start();
        //让主线程等待thread线程执行完毕之后再继续,join方法会让当前线程阻塞
        thread.join();

        //获取thread线程的执行结果
        Integer rs = result.getResult();
        System.out.println(System.currentTimeMillis());
        System.out.println(System.currentTimeMillis() + ":" + rs);
    }
}

Output:

1566733162636
1566733165692
1566733165692:10

Code by blocking the main thread join the current way, when a thread after thread is finished, join methods will continue.

join the way, you can only block a thread if the other threads also need to obtain the results thread thread, join methods do nothing to help.

About join () method and the use of threads in more detail, can refer to: the basic operation of the thread

Mode 2: CountDownLatch achieve

Code:

package com.itsoku.chat31;

import java.util.concurrent.*;

/**
 * 跟着阿里p7学并发,微信公众号:javacode2018
 */
public class Demo2 {
    //用于封装结果
    static class Result<T> {
        T result;

        public T getResult() {
            return result;
        }

        public void setResult(T result) {
            this.result = result;
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println(System.currentTimeMillis());
        CountDownLatch countDownLatch = new CountDownLatch(1);
        //用于存放子线程执行的结果
        Demo1.Result<Integer> result = new Demo1.Result<>();
        //创建一个子线程
        Thread thread = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
                result.setResult(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                countDownLatch.countDown();
            }
        });
        thread.start();
        //countDownLatch.await()会让当前线程阻塞,当countDownLatch中的计数器变为0的时候,await方法会返回
        countDownLatch.await();

        //获取thread线程的执行结果
        Integer rs = result.getResult();
        System.out.println(System.currentTimeMillis());
        System.out.println(System.currentTimeMillis() + ":" + rs);
    }
}

Output:

1566733720406
1566733723453
1566733723453:10

The above code is also achieved the desired results, use CountDownLatchcan make one or more threads wait for a number of threads after the completion of their own and then continue; CountDownLatchmore detail see: the JUC waiting multithreading tools CountDownLatch completed, the necessary skills

Mode 3: ExecutorService.submit method implementation

Code:

package com.itsoku.chat31;

import java.util.concurrent.*;

/**
 * 跟着阿里p7学并发,微信公众号:javacode2018
 */
public class Demo3 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //创建一个线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        System.out.println(System.currentTimeMillis());
        Future<Integer> future = executorService.submit(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 10;
        });
        //关闭线程池
        executorService.shutdown();
        System.out.println(System.currentTimeMillis());
        Integer result = future.get();
        System.out.println(System.currentTimeMillis() + ":" + result);
    }
}

Output:

1566734119938
1566734119989
1566734122989:10

Using the ExecutorService.submitmethod implemented, this method returns a Future, future.get()let the current thread to block until the task is completed to perform Future association.

related information:

  1. JAVA thread pool, this one is enough
  2. Detailed JUC frame 1 in the Executor
  3. Detailed JUC frame 2 in the Executor

Mode 4: FutureTask Mode 1

Code:

package com.itsoku.chat31;

import java.util.concurrent.*;

/**
 * 跟着阿里p7学并发,微信公众号:javacode2018
 */
public class Demo4 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println(System.currentTimeMillis());
        //创建一个FutureTask
        FutureTask<Integer> futureTask = new FutureTask<>(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 10;
        });
        //将futureTask传递一个线程运行
        new Thread(futureTask).start();
        System.out.println(System.currentTimeMillis());
        //futureTask.get()会阻塞当前线程,直到futureTask执行完毕
        Integer result = futureTask.get();
        System.out.println(System.currentTimeMillis() + ":" + result);
    }
}

Output:

1566736350314
1566736350358
1566736353360:10

Used in the code FutureTaskimplemented, FutureTask implements Runnablethe interface, and the internal return value, it can be passed to the Thread run directly futureTask.get()blocks the current thread until the FutureTasktask is completed the implementation of the constructor pass, get method will return. About FutureTaskdetails, please refer to: Executor framework JUC Comments 1

Mode 5: FutureTask Embodiment 2

Code:

package com.itsoku.chat31;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

/**
 * 跟着阿里p7学并发,微信公众号:javacode2018
 */
public class Demo5 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println(System.currentTimeMillis());
        //创建一个FutureTask
        FutureTask<Integer> futureTask = new FutureTask<>(() -> 10);
        //将futureTask传递一个线程运行
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            futureTask.run();
        }).start();
        System.out.println(System.currentTimeMillis());
        //futureTask.get()会阻塞当前线程,直到futureTask执行完毕
        Integer result = futureTask.get();
        System.out.println(System.currentTimeMillis() + ":" + result);
    }
}

Output:

1566736319925
1566736319970
1566736322972:10

Create an FutureTaskobject, call futureTask.get()will block the current thread, the child thread dormant for three seconds, and then call futureTask.run();when futureTask the run () method after finished, futureTask.get()returns from blocking.

Note: in this way and 4 way different points.

About FutureTaskdetails, please refer to: Executor framework JUC Comments 1

Way 6: CompletableFuture manner

Code:

package com.itsoku.chat31;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

/**
 * 跟着阿里p7学并发,微信公众号:javacode2018
 */
public class Demo6 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println(System.currentTimeMillis());
        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 10;
        });
        System.out.println(System.currentTimeMillis());
        //futureTask.get()会阻塞当前线程,直到futureTask执行完毕
        Integer result = completableFuture.get();
        System.out.println(System.currentTimeMillis() + ":" + result);
    }
}

Output:

1566736205348
1566736205428
1566736208429:10

CompletableFuture.supplyAsyncIt can be used to perform asynchronous tasks with a return value, callcompletableFuture.get()

Blocks the current thread until the task is finished, get method will return.

About CompletableFuturemore detailed usage, see: JUC in tools CompletableFuture, essential skills

java series of high concurrency directory

  1. Day 1: You must know a few concepts
  2. Day 2: concurrency level
  3. Day 3: Two important laws of the relevant parallel
  4. Day 4: JMM related concepts
  5. Day 5: In-depth understanding of processes and threads
  6. Basic operation thread: Day 6
  7. Day 7: volatile and Java Memory Model
  8. Day 8: Thread Group
  9. Day 9: user thread and thread guard
  10. Day 10: thread safe and synchronized keyword
  11. Day 11: thread interrupted in several ways
  12. Day 12 JUC: ReentrantLock reentrant lock
  13. Day 13: JUC Condition objects in
  14. Day 14: The JUC LockSupport tools, essential skills
  15. Day 15: Semaphore (semaphore) in JUC
  16. Day 16: JUC waiting in multithreading tools CountDownLatch completed, the necessary skills
  17. 17th day: circular fence in CyclicBarrier kinds scene JUC 6
  18. Day 18: JAVA thread pool, this one is enough
  19. Day 19: JUC Detailed frame 1 in Executor
  20. Day 20: JUC Detailed frame 2 in Executor
  21. Day 21: java in CAS, you need to know
  22. Day 22: JUC underlying tools Unsafe, master must understand
  23. Day 23: JUC class atom, an enough
  24. Day 24: ThreadLocal, InheritableThreadLocal (easy to understand)
  25. Day 25: JUC grasp of blocking queue
  26. The first 26: Learn to use a common set of JUC, often look!
  27. Day 27: actual articles, interfaces, performance times so simple
  28. Day 28: actual articles, pain micro service logs together to help you get rid of
  29. Day 29: concurrent high common mode current limit
  30. Day 30: JUC in tools CompletableFuture, essential skills

Ali p7 concurrent with the school, the public number: passerby java, get the latest articles every day!

Guess you like

Origin www.cnblogs.com/itsoku123/p/11412765.html