【正确答案】
【答案解析】Java虚拟机允许应用程序并发地运行多个线程。在Java语言中,多线程的实现一般有以下3种方法,其中前两种为最常用的方法。
(1)继承Thread类,重写run()方法
Thread本质上也是实现了Runnable接口的一个实例,它代表一个线程的实例,并且,启动线程的唯一方法就是通过Thread类的start()方法。start()方法是一个native(本地)方法,它将启动一个新线程,并执行run()方法(Thread中提供的run()方法是一个空方法)。这种方式通过自定义直接extend Thread,并重写run()方法,就可以启动新线程并执行自己定义的run()方法。需要注意的是,调用start()方法后并不是立即执行多线程代码,而是使得该线程变为可运行态(Runnable),什么时候运行多线程代码是由操作系统决定的。下例给出了Thread的使用方法:
class MyThread extends Thread{//创建线程类
public void run(){
System.out.println("Thread body"); //线程的函数体
}
}
public class Test{
public static void main(String[] args){
MyThread thread=new MyThread();
thread.start(); //开启线程
}
}
(2)实现Runnable接口,并实现该接口的run()方法
以下是主要步骤:
1)自定义类并实现Runnable接口,实现run()方法。
2)创建Thread对象,用实现Runnable接口的对象作为参数实例化该Thread对象。
3)调用Thread的start()方法。
class MyTbread implements Runnable{//创建线程类
public void run(){
System.out.println("Thread body");
}
}
public class Test{
public static void main(String[] args){
MyThread thread=new MyThread();
Thread t=new Thread(thread);
t.start();//开启线程
}
}
其实,不管是通过继承Thread类还是通过使用Runnable接口来实现多线程的方法,最终还是通过Thread的对象的API来控制线程的。
(3)实现Callable接口,重写call()方法
Callable接口实际是属于Executor框架中的功能类,Callable接口与Runnable接口的功能类似,但提供了比Runnable更强大的功能,主要表现为以下3点:
1)Callable可以在任务结束后提供一个返回值,Runnable无法提供这个功能。
2)Callable中的call()方法可以抛出异常,而Runnable的run()方法不能抛出异常。
3)运行Callable可以拿到一个Future对象,Future对象表示异步计算的结果,它提供了检查计算是否完成的方法。由于线程属于异步计算模型,因此无法从别的线程中得到函数的返回值,在这种情况下,就可以使用Future来监视目标线程调用call()方法的情况,当调用Future的get()方法以获取结果时,当前线程就会阻塞,直到call()方法结束返回结果。
import Java.util.concurrent.*;
public class CallableAndFuture{
//创建线程类
public static class CallableTest implements Callable<String>{
public String call()throws Exception{
return "Hello World!";
}
}
public static void main(String[]args){
ExecutorService threadPool=Executors.newSingleThreadExecutor();
//启动线程
Future<String>future=threadPool.submit(new CallableTest());
try{
System.out.println("waiting thread to finish");
System.out.println(future.get());//等待线程结束,并获取返回结果
}catch(Exception e){
e.printStackTrace();
}
}
}
上述程序的输出结果为:
waiting thread to finish
Hello World!
以上3种方式中,前两种方式线程执行完后都没有返回值,只有最后一种是带返回值的。当需要实现多线程时,一般推荐实现Runnable接口的方式,其原因是:首先,Thread类定义了多种方法可以被派生类使用或重写。但是只有run()方法是必须被重写的,在run()方法中实现这个线程的主要功能。这当然是实现Runnable接口所需的方法。其次,很多Java开发人员认为,一个类仅在他们需要被加强或修改时才会被继承。因此,如果没有必要重写Thread类中的其他方法,那么通过继承Thread的实现方式与实现Runnable接口的效果相同,在这种情况下最好通过实现Runnable接口的方式来创建线程。
引申:一个类是否可以同时继承Thread与实现Runnable接口?
答案:可以。为了说明这个问题,首先给出如下示例:
public class Test extends Thread implements Runnable{
public static void main(String args[]) {
Thread t=new Thread(new Test());
t.start();
}
}
从上例中可以看出,Test类实现了Runnable接口,但是并没有实现接口的run()方法,可能有些读者会认为这会导致编译错误,但实际它是能够编译通过并运行的,因为Test类从Thread类中继承了run()方法,这个继承的run()方法可以被当作对Runnable接口的实现,因此这段代码能够编译通过。当然也可以不使用继承的run()方法,而是需要通过在Test类中重写run()方法来实现Runnable接口中的run()方法,示例如下:
public class Test extends Thread implements Runnable{
public void run(){
System.out.println("this is run()");
}
public static void main(String args[]){
Thread t=new Thread(new Test());
t start();
}
}
程序运行结果为:
this is run()