例子代码:
java 代码
- 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;
- class TimeConsumingTask implements Callable {
- public Person call() throws Exception {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- Future future = executor.submit(new Callable<String>(){
- public String call() throws Exception {
- return "内部线程代码";
- }
- });
- String resultString = null;
- try {
- resultString = (String) future.get();
- System.out.printf("内部: %s\n", resultString);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (ExecutionException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return new Person(1,"彭帅");
- }
- }
- import java.io.DataOutputStream;
- import java.util.concurrent.ExecutionException;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.Future;
- public class PersonTest {
- public static void main(String[] args){
- ExecutorService executor = Executors.newSingleThreadExecutor();
- Future future = executor.submit(new TimeConsumingTask());
- Person resultPerson = null;
- try {
- resultPerson = (Person) future.get();
- resultPerson.move(Direction.DOWN);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (ExecutionException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- import java.util.Hashtable;
- public class Person {
- private static Hashtable<Direction, String> hashValues = new Hashtable<Direction, String>();
- static{
- for(Direction d: Direction.values()){
- hashValues.put(d, d.name());
- }
- }
- private long id;
- private String name;
- public Person(){
- }
- public Person(long id, String name) {
- super();
- this.id = id;
- this.name = name;
- }
- public long getId() {
- return id;
- }
- public void setId(long id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public void move(Direction direct){
- System.out.printf(this.name + " towarding %s", hashValues.get(direct));
- }
- }
- public enum Direction {
- UP, DOWN, LEFT, RIGHT;
- }