Skip to content

Commit

Permalink
threads callable
Browse files Browse the repository at this point in the history
  • Loading branch information
bejondshao committed Apr 16, 2016
1 parent 2c61407 commit e285545
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.bejond.threads.callable;

import java.util.concurrent.Callable;

/**
* Created by bejond on 4/16/16.
*
* If we want a thread return a value, we can make the thread implement
* Callable<T>.
*/
public class ReturnWithResultThread implements Callable {
private long id;

public ReturnWithResultThread(long id) {
this.id = id;
}

@Override
public Object call() throws Exception {
System.out.println("Invoke call()" + id);
return "The thread return result is " + id;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package com.bejond.threads.callable;

import org.junit.Test;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
* Created by bejond on 4/16/16.
*/
public class TestReturnWithResultThread {

@Test
public void testReturnThread() {

/**
* Executors.newCachedThreadPool() returns a ThreadPoolExecutor instance,
* ThreadPoolExecutor extends AbstractExecutorService, and
* AbstractExecutorService implements ExecutorService.
*/
ExecutorService executorService = Executors.newCachedThreadPool();

ArrayList<Future<String>> futureArrayList =
new ArrayList<Future<String>>();

for (int i = 0; i < 100; i++) {

/**
* AbstractExecutorService implements submit(Callable<T>).
* submit() invoke call().
*/
futureArrayList.add(
executorService.submit(new ReturnWithResultThread(i)));
}

System.out.println("Adding threads is done.");

for (Future<String> future : futureArrayList) {
try {
// get() blocks until completing task
System.out.println(future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} finally {
executorService.shutdown();
}
}
}
}

0 comments on commit e285545

Please sign in to comment.