轉(zhuǎn)載自
http://www.itdecent.cn/p/19f9ce1d82a4
繼承 Thread 類
run() 方法 VS start() 方法:
- run() 方法:普通的成員方法
- start() 方法:負(fù)責(zé)啟動(dòng)一個(gè)新的線程,并調(diào)用 run() 方法
- 因此啟動(dòng)線程,需要使用 start() 方法
public class MultiThread_Test {
public static void main(String[] args) {
MyThread mt = new MyThread();
mt.start();
}
}
class MyThread extends Thread {
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
實(shí)現(xiàn) Runnable 接口
實(shí)際上 Thread 類也是實(shí)現(xiàn)了 Runnable 接口:
class Thread implements Runnable {}
啟動(dòng) Runnable 實(shí)例時(shí),需要放在 Thread 中,然后調(diào)用 start() 方法
public class MultiThread_Test {
public static void main(String[] args) {
MyRunnable mr = new MyRunnable();
new Thread(mr).start();
}
}
class MyRunnable implements Runnable {
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
實(shí)現(xiàn) Callable 接口
- Java 5 開(kāi)始提供
- 可以返回結(jié)果(通過(guò) Future),也可以拋出異常
- 需要實(shí)現(xiàn)的是 call() 方法
- 以上兩點(diǎn)也是 Callable 接口 與 Runnable 接口的區(qū)別
public class MultiThread_Test {
public static void main(String[] args) throws Exception {
ExecutorService es = Executors.newSingleThreadExecutor();
// 自動(dòng)在一個(gè)新的線程上啟動(dòng) MyCallable,執(zhí)行 call 方法
Future<Integer> f = es.submit(new MyCallable());
// 當(dāng)前 main 線程阻塞,直至 future 得到值
System.out.println(f.get());
es.shutdown();
}
}
class MyCallable implements Callable<Integer> {
public Integer call() {
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 123;
}
}