注意:
1.實現(xiàn)Runnable接口創(chuàng)建線程沒有直接的返回值,但可以通過額外添加成員變量和get方法實現(xiàn)同樣的效果。
2.如果run方法內(nèi)有異常不能拋出,要在內(nèi)部直接抓取。
1.實現(xiàn)Callable接口創(chuàng)建線程的簡單實現(xiàn):
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;
public class MyThread {
public static void main(String[] args) throws InterruptedException, ExecutionException {
//創(chuàng)建線程
ExecutorService executorService = Executors.newFixedThreadPool(1);
Race tortoise = new Race();
//獲取值
Future<Integer> future = executorService.submit(tortoise);
int sum = future.get();
System.out.println(sum);
executorService.shutdown();
}
}
class Race implements Callable<Integer>{
@Override
public Integer call() throws Exception {
// TODO Auto-generated method stub
return 1000;
}
}
2.實現(xiàn)Callable接口創(chuàng)建線程的復(fù)雜實現(xiàn):
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;
public class MyThread {
public static void main(String[] args) throws InterruptedException, ExecutionException {
//創(chuàng)建線程
ExecutorService executorService = Executors.newFixedThreadPool(2);
Race tortoise = new Race("烏龜", 1000);
Race rabbit = new Race("兔子", 500);
//獲取值
Future<Integer> tortoiseFuture = executorService.submit(tortoise);
Future<Integer> rabbitFuture = executorService.submit(rabbit);
Thread.sleep(2000);//2秒
tortoise.setFlag(false);//停止線程體循環(huán)
rabbit.setFlag(false);
int tortoiseSum = tortoiseFuture.get();
int rabbitSum = rabbitFuture.get();
System.out.println("烏龜跑了:" + tortoiseSum + "步。");
System.out.println("兔子跑了:" + rabbitSum + "步。");
executorService.shutdown();
}
}
class Race implements Callable<Integer>{
private String name;//名稱
private long time;//延遲時間
private boolean flag = true;//是否繼續(xù)走
private int step;//步
public Race(String name, long time) {
this.name = name;
this.time = time;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
@Override
public Integer call() throws Exception {
// TODO Auto-generated method stub
while(flag) {
Thread.sleep(time);//延遲
step++;
}
return step;
}
}
更多建議: