package MultiThread;
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;
class MyCallable implements Callable{
int pauseTime;
String name;
MyCallable(int x, String n) {
this.name = n;
this.pauseTime = x;
}
@Override
public Object call() throws Exception {
int i = 0;
while(i++<10) {
System.out.println(name + ":" + new Date(System.currentTimeMillis()));
try {
Thread.sleep(pauseTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return name + " returned";
}
}
public class CallableTest {
/**
* @param args
* @throws ExecutionException
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException, ExecutionException {
// TODO Auto-generated method stub
ExecutorService pool = Executors.newFixedThreadPool(2);
Callable c1 = new MyCallable(1000, "Fast Guy");
Callable c2 = new MyCallable(3000, "Slow Guy");
Future f1 = pool.submit(c1);
Future f2 = pool.submit(c2);
System.out.println("task submit");
System.out.println(">>>"+f1.get());
System.out.println(">>>"+f2.get());
System.out.println("end");
pool.shutdown();
}
}