- 多线程有三种实现方式:
- 直接继承Thread 类
- 实现Runnable 接口 --无返回值 无异常操作
- 实现Callable 接口 --有返回值 有异常操作
话不多说 第一种就不说了 说下下面的两种:
- 实现Runnable 接口
- 实现Callable 接口
- 下面的demo 可以直观的显示实现的过程
package threadPool;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class MyThread {
public static void main(String[] args) throws ExecutionException, InterruptedException {
for (int i = 0; i < 5; i++) {
MyCallable myCallable = new MyCallable();
FutureTask<Integer> ft = new FutureTask(myCallable);
new Thread(ft).start();
System.out.println(ft);
System.out.println(ft.isDone());
System.out.println(ft.get());
}
MyThread.MyRunnable myRunnable= new MyRunnable();
MyRunnable myRunnable1 = new MyRunnable();
for (int i = 0; i < 5; i++) {
new Thread(myRunnable1).start();
}
}
static private class MyCallable implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("子线程在计算。。。");
System.out.println(Thread.currentThread().getName());
int sum = 0;
for (int i = 0; i < 100; i++) {
sum += i;
}
System.out.println(sum);
System.out.println(new Integer(sum));
return new Integer(sum);
}
}
static private class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
}