Created
December 18, 2014 03:11
-
-
Save guodong1111/915e0a75a145d72a5948 to your computer and use it in GitHub Desktop.
This file contains 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.io.BufferedReader; | |
import java.io.InputStreamReader; | |
import java.net.URL; | |
import java.net.URLConnection; | |
import java.util.concurrent.Callable; | |
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
import java.util.concurrent.Future; | |
public class CallableAndFuture | |
{ | |
public static void main(String[] args) | |
{ | |
ExecutorService threadpool = Executors.newFixedThreadPool(1); | |
System.out.println("main_1"); | |
Callable<String> callable = new Callable<String>() | |
{ | |
public String call() throws Exception | |
{ | |
System.out.println("call_start"); | |
URL oracle = new URL("http://www.google.com/"); | |
URLConnection yc = oracle.openConnection(); | |
BufferedReader in = new BufferedReader(new InputStreamReader( | |
yc.getInputStream())); | |
String inputLine; | |
while ((inputLine = in.readLine()) != null) ; | |
in.close(); | |
System.out.println("call_finish"); | |
return inputLine; | |
} | |
}; | |
System.out.println("main_2"); | |
Future<String> future = threadpool.submit(callable); | |
System.out.println("main_3"); | |
try | |
{ | |
System.out.println("1"); | |
Thread.sleep(3000); | |
System.out.println("2"); | |
System.out.println("isDone: "+future.isDone()); | |
System.out.println("get: "+future.get()); | |
System.out.println("3"); | |
} | |
catch (Exception e) | |
{ | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment