Java中创建多线程的三种方法:
-
继承 Thread 类
class MyThread extends Thread{ @Override public void run() { // TODO Auto-generated method stub super.run(); } }
调用方法
public static void main(String[] args) {
MyThread my = new MyThread();
my.start();
}
-
实现 Runnable 接口
class MyRunnable implements Runnable{ @Override public void run() { // TODO Auto-generated method stub } }
调用方法
public static void main(String[] args) {
MyRunnable my = new MyRunnable ();
new Thread(my).start();
}
-
实现 Callable<?> 接口,支持返回结果,支持泛型
public class MyCallable implements Callable<String>{ @Override public String call() throws Exception { String[] str = {"First", "Second", "Third", "Fourth", "Five"}; int index = (int) (Math.random() * 5); return str[index]; } }
调用该类
public static void main(String[] args) {
//创建任务
MyCallable mc = new MyCallable();
//将任务交给任务管理器
//FutureTask<?> 是一个管理类,实现了RunnableFuture<?>接口;
//而RunnableFuture<?>接口,实现了Runnable, Future<V>两个接口
FutureTask<String> ft = new FutureTask<>(mc);
new Thread(ft).start();
try {
//获取线程任务的执行结果
System.out.println(ft.get());
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//判断线程任务执行是否结束
System.out.println(ft.isDone());
}
网友评论