Simple implementation of multithreading with return value

package com.zkingcai.pay;

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

/**
 * ***************************************************************************
 *Created: April 28, 2018
 *Implementation function: Implement Callable, create a task with a return value
 *Author: sxl
 *Version: v0.0.1
-----------------------------------------------------------------------------
 *Modification record:
 *Date version modified by modified content
 * April 28, 2018 v0.0.1 sxl created
 ****************************************************************************
 */
class MyCallable implements Callable<String>{

	@Override
	public String call() throws Exception {
		Date time1 = new Date();
		Thread.sleep(1000);
		Date time2 = new Date();
		return Thread.currentThread().getName() + "running" + (time2.getTime() - time1.getTime()) + "milliseconds";
	}
	 
}

/**
 * ***************************************************************************
 *Created: April 28, 2018
 * Implemented function: get thread pool, execute thread, return result
 *Author: sxl
 *Version: v0.0.1
-----------------------------------------------------------------------------
 *Modification record:
 *Date version modified by modified content
 * April 28, 2018 v0.0.1 sxl created
 ****************************************************************************
 */
public class ThreadDemo {
	
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		
		// get the thread pool
		ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(1);
		// create task
		MyCallable myCallable = new MyCallable();
		// execute the task
		Future<String> future = newFixedThreadPool.submit(myCallable);
		// get the return value
		String result = future.get();
		System.out.println(result);
	}
}

returned result


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325857819&siteId=291194637