Last active
December 17, 2015 19:19
-
-
Save akirad/5660042 to your computer and use it in GitHub Desktop.
A sample program using "Future" of Java. The result of this program is (e.g.) as follows. Execute a task...
Execute other task.
Task started.
Task Ended.
Other task finished.
Time(Task result) is Mon May 27 19:43:41 MDT 2013
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
public class FutureSample { | |
public static void main(String[] args) { | |
try{ | |
FutureSample futureSample = new FutureSample(); | |
futureSample.exec(); | |
} | |
catch(Exception ex){ | |
System.out.println(ex.getMessage()); | |
System.out.println(ex.getStackTrace()); | |
} | |
} | |
private void exec() throws InterruptedException, ExecutionException { | |
//-------------------------------- | |
// Definition of a task(Callable). | |
//-------------------------------- | |
Callable<Date> task = new Callable<Date>() { | |
public Date call() throws InterruptedException { | |
System.out.println("Task started."); | |
Thread.sleep(3000); | |
Date time = new Date(); | |
System.out.println("Task Ended."); | |
return time; | |
} | |
}; | |
ExecutorService executor = Executors.newSingleThreadExecutor(); | |
// Execute the task and get a future for the task. | |
System.out.println("Execute a task..."); | |
Future<Date> future = executor.submit(task); | |
// Other tasks can be done with the task here, and this fact is important for using Future. | |
System.out.println("Execute other task."); | |
Thread.sleep(5000); | |
System.out.println("Other task finished."); | |
// Get the result of the task if it has been done. Otherwise this thread waits here. | |
Date time = future.get(); | |
System.out.println("Time(Task result) is " + time); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment