Java中多线程实现的方式主要有三种:
- 继承Thread类
- 实现Runnable接口
- 使用ExecutorService、Callable、Future实现有返回结果的多线程
其中前两种方式线程执行完没有返回值,只有最后一种是带返回值的。
继承Thread类本质上也是实现Tunnable接口的一个实例,他代表一个线程的实例,并且启动线程的唯一方法是通过Thread类的start()方法,start()方法是一个native方法,他将启动一个新线程,并执行run( )方法。
实例化一个Thread对象,并传入实现的Runnable接口,当传入一个Runnable target参数给Thread后,Thraed的run()方法就会调用target.run( );
可返回值的任务必须实现Callable接口,类似的无返回值的任务必须实现Runnable接口,执行Callable任务后,可以获取一个Future的对象,在该对象上调用get就可以获取到Callable任务返回的Object了,在结合线程池接口ExecutorService就可以实现有返回结果的多线程。
#继承 Thread 类本身
public class 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());
}
}
#实现Runnable接口 *用法需要在外层包裹一层 Thread *
public class 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());
}
}
#实现 Callable 接口 比较少见,不常用 需要实现的是 call() 方法
代码拷过来的,确实没用过
public class Test {
public static void main(String[] args) throws Exception {
ExecutorService es = Executors.newSingleThreadExecutor();
// 自动在一个新的线程上启动 MyCallable,执行 call 方法
Future<Integer> f = es.submit(new MyCallable());
// 当前 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;
}
}