Java虚拟机允许应用程序并发地运行多个线程。在Java中,多线程的实现一般有以下3中方法:
1、继承Thread类,重写run()方法:
Thread本质上也是实现了Runnable接口的一个实例,他代表一个线程的实例,而且启动线程的唯一方法就是通过Thread类start()方法。start()方法就是一个本地native(本地)方法,它将启动一个新线程,并执行run()方法。run()方法算是一个空方法。
这种方式就是通过自定义直接extend Thread,然后重写run()方法,就可以启动新线程并执行自己定义的run()方法。
注意:调用start()方法并不是立即执行多线程代码,而是使得该线程变为可运行态(Runable),什么时候运行多线程代码是由操作系统决定的。
package threadDemo;
class MyThread extends Thread{
public void run() {
System.out.println("first thread!");
}
}
public class demo01 {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
2、实现Runnable接口,并实现该接口的run()方法,具体步骤见下:
(1)自定义并实现Runnable接口,实现run()方法;
(2)创建Thread对象,用实现Runable接口的对象作为参数实例化该Thread对象。
(3)调用Thread的start()方法;
package threadDemo;
class thread implements Runnable{
public void run() {
System.out.println("second thread!");
}
}
public class demo02 {
public static void main(String[] args) {
thread t = new thread();
Thread thread = new Thread(t);
thread.start();
}
}
3、实现Callable接口,重写call()方法:
Callable接口实际属于Excutor框架中的功能,Callable接口与Runnable接口的功能类似,但提供了比Runnable更强大的功能,主要表现在以下三点。
1)Callable可以在任务结束后提供一个返回值,Runnable无法提供这个功能。
2)Callable中的call()方法能够抛出异常,而Runnable中的run()方法则不能。
3)运行Callable可以拿到一个Future对象,Future对象表示异步计算结果,他提供了检查计算是否完成的方法。由于线程属于意不计算模型,因此无法从别的线程中得到函数的返回值,在这种情况下,就可以使用Future来监视目标线程调用call()方法的情况,当调用Future的get()方法以获取结果,当前县城就会阻塞,直到call()方法结束返回结果。
package threadDemo;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class demo03 {
//创建线程
public static class CallableTest implements Callable<Integer>{
public Integer call() throws Exception{
return 2;
}
public static void main(String[] args) {
ExecutorService threadpool = Executors.newSingleThreadExecutor();
//启动线程
Future<Integer> future = threadpool.submit(new CallableTest());
try {
System.out.println("waiting thread to finish");
System.out.println(future.get());
//等待线程结束,并获取返回结果
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}
下面的代码能够欧通过编译,因为Test类从Thread类中继承了run()方法,这个继承的run()方法是可以被当做Runnable接口的实现。
public class Test extends Thread implements{
public static void main(String args[]){
Thread t = new Thread(new Test());
}
总结:
当需要实现多线程的时候,一般推荐实现Runnable接口的方式,原因:
(1)首先,Thread类定义了多中方法可以被派生类使用或者重写。但是只有run()方法时必须被重写的,在run()方法中实现这个县城的主要功能.
(2)一个类仅在需要时被加强,或者修改时才会被继承。一次 ,如果没有必要重写Thread类中的其他方法,那么通过继承Thread的实现方式与实现Runnable接口的效果相同,在这种情况下最好通过实现Runnable接口的方式来创建线程。

被折叠的 条评论
为什么被折叠?



