004.多執行緒-執行緒的三種建立方式
阿新 • • 發佈:2018-12-21
1. extend Thread
package cn.qbz.thread;
public class ExtendThreadTest {
public static void main(String[] args) {
ExtendThread thread = new ExtendThread();
thread.start();
for (int i = 0; i < 300; i++) {
System.out.println("主執行緒:" + Thread.currentThread().getName () + " " + i);
}
}
}
class ExtendThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 300; i++) {
System.out.println("子執行緒:" + this.getName() + " " + i);
}
}
}
2. implement Runnable
package cn.qbz.thread;
public class ImplementRunnableTest {
public static void main(String[] args) {
ImplementRunnable runnable = new ImplementRunnable();
Thread thread = new Thread(runnable);
thread.start();
for (int i = 0; i < 300; i++) {
System.out.println("主執行緒:" + Thread.currentThread().getName() + " " + i);
}
}
}
class ImplementRunnable implements Runnable {
public void run() {
for (int i = 0; i < 300; i++) {
System.out.println("子執行緒:" + Thread.currentThread().getName() + " " + i);
}
}
}
3.implement Callable
package cn.qbz.thread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeoutException;
public class ImplementCallableTest {
public static void main(String[] args) {
ImplementCallable callable = new ImplementCallable(666);
FutureTask<Integer> futureTask = new FutureTask<Integer>(callable);
Thread thread = new Thread(futureTask);
thread.start();
for (int i = 0; i < 300; i++) {
System.out.println("主執行緒:" + Thread.currentThread().getName() + " " + i);
}
try {
System.out.println("子執行緒返回值:" + futureTask.get());
} catch (InterruptedException e) {
System.out.println("eeeeeeeeeeeeee222....." + e.getMessage());
} catch (ExecutionException e) {
System.out.println("eeeeeeeeeeeeee....." + e.getMessage());
}
for (int j = 0; j < 10; j++) {
System.out.println("jjjjjjjjjjj " + j);
}
}
}
class ImplementCallable implements Callable<Integer> {
private Integer result;
public ImplementCallable(Integer result) {
this.result = result;
}
public Integer call() throws Exception {
for (int i = 0; i < 300; i++) {
System.out.println("子執行緒:" + Thread.currentThread().getName() + " " + i);
if (i == 268) {
throw new TimeoutException();
}
}
return result;
}
}
- Implement Callable,重寫call方法,不但可以返回值,還可以丟擲異常。
- 丟擲的異常,在futureTask.get()中被捕獲
- futureTask.get()在執行的過程中會阻塞,一直到所線上程執行結束
- futureTask還有相關方法來進行了解執行緒的執行情況
三種建立方式的比較:
當前主流的就是面向介面開發, 因為實現了介面後還可以根據業務需要再繼承其他的類。 實現Runnable接庫與實現Callable介面對比來看, Callable介面有幾個優勢,也就是上面所說的: 可返回值,可丟擲異常,可瞭解執行緒執行情況。