Java多執行緒之旅(一)
阿新 • • 發佈:2019-02-11
public class CallableExample implements Callable<Integer> {
private Integer num = 100;
@Override
public Integer call() throws Exception {
for (int i = 0; i < num; i++) {
num--;
System.out.println(Thread.currentThread().getName() + ":" + num);
}
return num;
}
}
public class CallableExampleTest { public static void main(String[] args) throws InterruptedException, ExecutionException { Callable<Integer> callable = new CallableExample(); FutureTask<Integer> target1 = new FutureTask<>(callable); FutureTask<Integer> target2 = new FutureTask<>(callable); Thread thread1 = new Thread(target1, "子執行緒1"); thread1.start(); Thread thread2 = new Thread(target2, "子執行緒2"); thread2.start(); System.out.println("子執行緒1--call方法返回值:" + target1.get()); System.out.println("子執行緒2--call方法返回值:" + target2.get()); } }