ExecutorService, Callable, Future support for threads in JDK

1. Code background:

    If there are four threads Thread1, Thread2, Thread3, and Thread4 to count the sizes of the four disks C, D, E, and F respectively, and all the threads are counted and handed over to the Thread5 thread for summarization, how should it be implemented?

2. Code:

    The code to count the size of the "plate", here implements the Callable interface in jdk,

package com.wang.test.concurrent;

import java.util.concurrent.Callable;

public class Task1 implements Callable<Integer> {

	private int x;
	private int y;
	
	public Task1(int x, int y) {
		this.x = x;
		this.y = y;
	}

	@Override
	public Integer call() throws Exception {
		return x*y;
	}

}

    The code for statistical summary also implements the Callable interface in jdk,

package com.wang.test.concurrent;

import java.util.concurrent.Callable;

public class Task2 implements Callable<Integer> {

	private int x;
	private int y;
	private int q;
	private int w;
	
	public Task2(int x, int y, int q, int w) {
		this.x = x;
		this.y = y;
		this.q = q;
		this.w = w;
	}

	@Override
	public Integer call() throws Exception {
		return x + y + q + w;
	}

}

      Client: Use the Executors.newFixedThreadPool method in the JDK to create an ExecutorService, and the submit method of the ExecutorService receives the implementation of the Callable interface. The JDK will make thread processing, and use the Future to receive the return value of the submit method. When the future calls the get method, if the thread still If it is not finished, the program blocks here until the thread is finished.

package com.wang.test.concurrent;

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

public class Client {

	public static void main(String[] args) throws Exception {
		ExecutorService pool = Executors.newFixedThreadPool(4);

		Task1 t1 = new Task1(1,2);
		Task1 t2 = new Task1(23,34);
		Task1 t3 = new Task1(23,456);
		Task1 t4 = new Task1(3,33);
		Future<Integer> f1 = pool.submit(t1);
		Future<Integer> f2 = pool.submit(t2);
		Future<Integer> f3 = pool.submit(t3);
		Future<Integer> f4 = pool.submit(t4);
		
		//When Future calls the get method, if the thread has not finished executing, the program blocks here
		Task2 t5 = new Task2(f1.get(), f2.get(), f3.get(), f4.get());
		Future<Integer> f5 = pool.submit(t5);
		
		System.out.println(f5.get());
		
		pool.shutdown();
	}
}

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326809831&siteId=291194637