一、使用线程
有三种使用线程的方法:
- 实现 Runnable 接口
- 实现 Callable 接口
- 继承 Thread 类
实现 Runnable 和 Callable 接口的类是在在线程中运行的任务,不是真正意义上的线程,最后还需要通过 Thread 来调用。可以理解为任务是通过线程驱动从而执行的。
实现 Runnable 接口
任务的实现在run方法中
public class MyRunnable implements Runnable {
@Override
public void run() {
// 代码块
}
}
使用 Runnable 实例再创建一个 Thread 实例,然后调用 Thread 实例的 start() 方法来启动线程。
public static void main(String[] args) {
MyRunnable instance = new MyRunnable();
Thread thread = new Thread(instance);
thread.start();
}
实现 Callable 接口
可以有返回值,通过 FutureTask 进行封装,获得程序执行的结果。
public interface Callable<V> {
//泛型接口,call()函数返回的类型就是传递进来的V类型。
V call() throws Exception;
}
public class MyCallable implements Callable<Integer> {
public Integer call() {
//...
return 123;
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyCallable mc = new MyCallable();
FutureTask<Integer> ft = new FutureTask<>(mc);
Thread thread = new Thread(ft);
thread.start();
System.out.println(ft.get());
}
继承 Thread 类
同样也是需要实现 run() 方法,因为 Thread 类也实现了 Runable 接口。
当调用 start() 方法启动一个线程时,虚拟机会将该线程放入就绪队列中等待被调度,当一个线程被调度时会执行该线程的 run() 方法。
public class MyThread extends Thread {
public void run() {
// ...
}
}
public static void main(String[] args) {
MyThread mt = new MyThread();
mt.start();
}
实现接口 VS 继承 Thread
实现接口会更好一些,因为:
- Java 不支持多重继承,因此继承了 Thread 类就无法继承其它类,但是可以实现多个接口;
- 类可能只要求可执行就行,继承整个 Thread 类开销过大。
认识多线程中的 start() 和 run()
用start方法来启动线程,真正实现了多线程运行,这时无需等待run方法体中的代码执行完毕而直接继续执行后续的代码。通过调用Thread类的 start()方法来启动一个线程,这时此线程处于就绪(可运行)状态,并没有运行,一旦得到cpu时间片,就开始执行run()方法,这里的run()方法 称为线程体,它包含了要执行的这个线程的内容,Run方法运行结束,此线程随即终止。