📄 futureexample.java
字号:
/** * Example code for JavaOne hands-on J2SE lab * * Concurrency utilities (JSR-166) example **/package future;import java.net.*;import java.io.*;import java.util.concurrent.*;/** * Demonstration of the use of a Future to return the results from a * Callable. This shows the simplicity of synchronising two concurrent * threads **/public class FutureExample { /** * Constructor **/ public FutureExample() { } /** * Run the test **/ public void runTest() { /* Use the Executors utility method to get an ExecutorService for a * separate thread of execution */ ExecutorService threadExecutor = Executors.newSingleThreadExecutor(); System.out.println("Starting test in first thread"); /* Now attempt to run a task in the second thread */ try { Future<String> future = threadExecutor.submit(new CallableExample()); /* Set this sleep to either 100 0r 1000 to see the synchronisation * effects */ Thread.sleep(1000); System.out.println("First thread work complete. Asking future for result"); String result = future.get(); System.out.println("Result from Future is " + result); } catch (Exception e) { System.out.println("Got an exception executing the test"); System.out.println(e.getMessage()); } /* Shutdown the second thread so the program terminates gracefully */ threadExecutor.shutdown(); } /** * Main entry point * * @param args The command line arguments **/ public static void main(String[] args) { FutureExample fe = new FutureExample(); fe.runTest(); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -