在学习多线程前,需要知道为啥要用多线程,多线程的优点是什么?
使用多任务操作系统(windows,ios)等,都可以最大限度的利用CPU空闲时间来出来其他任务,比如一边让操作系统处理打印机正在打印的数据,一边使用Word编辑文档。而CPU在这些任务之间不停的切换,由于切换的速度非常快,给使用者感受这些任务都是在同时运行。所以使用多线程,可以在同一时间处理多个任务,使系统的运行效率大大提升。
线程一个最大的特点:随机性。线程什么时候获得执行权是随机的。
Java多线程的创建方式有四种:继承Thread类、实现Runnable接口、实现Callable接口通过FutureTask包装器来创建有返回值的Thread线程、使用ExecutorService、Callable、Future实现有返回结果的多线程。
1. 继承Thread类创建多线程
将类声明为 Thread 的子类。该子类应重写 Thread 类的 run 方法。接下来可以分配并启动该子类的实例,通过Thread类的start()方法启动线程,start()方法是个本地方法。
public class MyThread extends Thread{
@Override
public void run() {
System.out.println(getName());
}
public static void main(String[] args) {
MyThread myThread1 = new MyThread();
MyThread myThread2 = new MyThread();
myThread2.start();
myThread1.start();
}
}
如果一个线程多次调用会报:IllegalThreadStateException。
2. 实现Runnable接口创建多线程
继承Thread类开发多线程应用程序是有局限性的,因为Java是单根继承,不支持多根继承。所以为了改变这种限制,可以通过实现接口的方式实现多线程。
如果一个类型已经继承了其他类型,就可以通过实现Runnable接口来实现。
public class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
Thread thread2 = new Thread(myRunnable);
thread.start();
thread2.start();
}
}
实现了Runnable接口的类,启动新线程的时候,就要将该实例作为参数传递给Thread的构造方法,通过创建Thread实例启动新线程。
看JDK源码是如何通过Thread实例启动实现了Runnable接口的线程。Thread类中部分代码:
private Runnable target;
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
private void init(ThreadGroup g, Runnable target, String name,
long stackSize) {
...
this.target = target;
...
}
public void run() {
if (target != null) {
target.run();
}
}
我们发现Thread有个带Runnable类型参数的构造方法,通过这个构造方法就可以给Thread类中的target初始化值。通过这个构造方法创建一个新线程,调用start()方法启动线程的时候,就调用Thread类型的run()方法,此时target不为null,所以调用的是Runnable接口实现类的run()方法。
Thread类的构造方法不光可以传入Runnable接口的对象,还可以传入一个Thread对象,这样完全可以将一个Thread对象的run()方法交给其他线程进行调用。
3. 实现Callable接口
实现Callable接口,复写call()方法,该方法有返回值,根据指定实现Callable接口时的泛型锁定。
创建Callable接口实现类的实例,通过FutureTask包装该实例。然后将FutureTask实例通过参数传递给Thread类的构造方法,创建新的线程,通过调用Thread类的start()方法启动线程。
可以通过FutureTask类的get()方法获取call()方法返回值。
public class MyCallable implements Callable<String>{
@Override
public String call() throws Exception {
String name = Thread.currentThread().getName();
return name;
}
public static void main(String[] args)
throws InterruptedException, ExecutionException {
MyCallable myCallable = new MyCallable();
FutureTask<String> futureTask = new FutureTask<String>(myCallable);
Thread thread = new Thread(futureTask);
thread.start();
System.out.println(futureTask.get());
}
}
看JDK源码可以知道,FutureTask实现了Runnable接口,所以可以将FutureTask作为实例传递给Thread类构造方法。
public interface RunnableFuture<V> extends Runnable, Future<V> {
/**
* Sets this Future to the result of its computation
* unless it has been cancelled.
*/
void run();
}
public class FutureTask<V> implements RunnableFuture<V> {
...
}
4. 使用ExecutorService、Callable、Future实现有返回结果的线程
ExecutorService、Callable、Future三个接口实际上都是属于Executor框架。返回结果的线程是在JDK1.5中引入的新特征,有了这种特征就不需要再为了得到返回值而大费周折了。而且自己实现了也可能漏洞百出。
可返回值的任务必须实现Callable接口。类似的,无返回值的任务必须实现Runnable接口。
执行Callable任务后,可以获取一个Future的对象,在该对象上调用get就可以获取到Callable任务返回的Object了。
注意:get方法是阻塞的,即:线程无返回结果,get方法会一直等待。
再结合线程池接口ExecutorService就可以实现传说中有返回结果的多线程了。
public class MyExecutor implements Callable<Object>{
@Override
public Object call() throws Exception {
return Thread.currentThread().getName();
}
@SuppressWarnings("rawtypes")
public static void main(String[] args)
throws InterruptedException, ExecutionException {
// 创建容量为3的定长线程池
ExecutorService pool = Executors.newFixedThreadPool(3);
// 创建有多个返回值的任务
List<Future> futures = new ArrayList<Future>();
for (int i = 0; i < 3; i++) {
Future<Object> future = pool.submit(new MyExecutor());
futures.add(future);
}
// 关闭线程池
pool.shutdown();
// 获取返回值
for (Future future : futures) {
System.out.println(future.get());
}
}
}