多線程
1.多線程有什麼用
(1)發揮多核CPU的優勢
(2)防止程序阻塞
(3)便於建立程序模型
2.創建多線程的方式.
3.start()與run()的區別
只有調用了start()方法,纔會表現出多線程的特性,不同線程的run()方法裏面的代碼交替執行。如果只是調用run()方法,那麼代碼還是同步執行的,必須等待一個線程的run()方法裏面的代碼全部執行完畢之後,另外一個線程纔可以執行其run()方法裏面的代碼
4.Runnable接口與Callable接口的區別
Runnable接口中的run()方法的返回值是void,它做的事情只是純粹地去執行run()方法中的代碼而已;Callable接口中的call()方法是有返回值的,是一個泛型,和Future、FutureTask配合可以用來獲取異步執行的結果
Callable規定的方法是call(),Runnable規定的方法是run().
Callable的任務執行後可返回值,而Runnable的任務是不能返回值得
call方法可以拋出異常,run方法不可以
運行Callable任務可以拿到一個Future對象,表示異步計算的結果。它提供了檢查計算是否完成的方法,以等待計算的完成,並檢索計算的結果。通過Future對象可以瞭解任務執行情況,可取消任務的執行,還可獲取執行結果。
ExecutorService 在Callable中使用的是submit(), 在Runnable中使用的是 execute()
Callable
package cn.Callable;
import java.util.concurrent.Callable;
public class SomeCallable implements Callable<String> {
private int id;
public SomeCallable(int id){
this.id=id;
}
@Override
public String call() {
return "武存健"+id;
}
package cn.Callable;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class SomeCallableTest {
/**
* @param args
* @throws ExecutionException
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException, ExecutionException {
//創建線程池
ExecutorService exec=Executors.newCachedThreadPool();
//Future<V> 相當於接收Executors結果的容器
ArrayList<Future<String>> result=new ArrayList<Future<String>>();
for (int i = 0; i < 10; i++) {
result.add(exec.submit(new SomeCallable(i)));
}
for (Future<String> fs : result) {
if (fs.isDone()) {
System.out.println(fs.get());
} else {
System.out.println("Future result is not yet complete");
}
}
exec.shutdown();
}
}
Runnable
package cn.Callable;
public class SomeRunnable implements Runnable {
protected int countDown = 10;
private static int taskCount = 0;
private final int id = taskCount++;
public SomeRunnable() {
}
public SomeRunnable(int countDown) {
this.countDown = countDown;
}
public String status() {
return "#" + id + "(" + (countDown > 0 ? countDown : "LiftOff! ") + ")";
}
@Override
public void run() {
while (countDown-- > 0) {
System.out.print(status());
Thread.yield();
}
System.out.println();
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SomeRunableTest {
public static void main(String[] args) {
//創建線程池
ExecutorService exec = Executors.newFixedThreadPool(1);
for (int i = 0; i < 5; i++) {
exec.execute(new SomeRunnable());
}
exec.shutdown();
}
}