实现多线程有三种方式:
- 实现Runnable接口并重写run()方法
- 继承Thread类并重写run()方法
- 实现callable接口并重写call()方法
下面我们将学习如何使用这三种方法:
一、继承Thread类方式
继承Thread类需要重写其run()方法,将线程需要执行的内容放在其run()方法内,一般是一个循环
优点:编写简单,如果需要访问当前线程,无需使用Thread.currentThread()方法,直接使用this,即可获得当前线程。
缺点:因为自定义线程类已经继承了Thread类,所以不能再继承其他的父类。
public class LiftOff extends Thread {
protected int countDown = 100;
private static int taskCount = 0;
private final int id = taskCount++;
public LiftOff() {}
public LiftOff(int countDown) {
this.countDown = countDown;
}
public String status() {
return "id:" + id + "(" + (countDown > 0 ? countDown : "发射!") + ")";
}
@Override
public void run() {
while(this.countDown-->0){
System.out.println(this.status());
}
}
}
public class Test {
@org.junit.Test
public void test() {
LiftOff thread=new LiftOff();
thread.start();
}
}
二、实现Runnable接口的方式
和继承Thread类一样,都需要重写run()方法
优点:线程类只是实现了Runable接口,还可以继承其他的类。在这种方式下,可以多个线程共享同一个目标对象,所以非常适合多个相同线程来处理同一份资源的情况,从而可以将CPU代码和数据分开,形成清晰的模型,较好地体现了面向对象的思想。
缺点:编程稍微复杂,如果需要访问当前线程,必须使用Thread.currentThread()方法。
public class LiftOff implements Runnable {
protected int countDown = 100;
private static int taskCount = 0;
private final int id = taskCount++;
public LiftOff() {}
public LiftOff(int countDown) {
this.countDown = countDown;
}
public String status() {
return "id:" + id + "(" + (countDown > 0 ? countDown : "发射!") + ")";
}
@Override
public void run() {
while(this.countDown-->0){
System.out.println(this.status());
}
}
}
public class Test {
@org.junit.Test
public void test() {
LiftOff thread=new LiftOff();
new Thread(thread).start();
}
}
三、实现callable接口的方式
Callable接口实际上是属于Executor框架中的功能类,Callable接口与Runnable接口的功能类似,但提供了比Runnable更加强大的功能。
public interface Callable<V> {
V call() throws Exception;
}
public interface Runnable {
public abstract void run();
}
从上面的接口声明我们就可以看出Callable接口和Runnable接口的不同:
- 实现Callable接口的任务线程能返回执行结果;而实现Runnable接口的任务线程不能返回结果;
- Callable接口的call()方法允许抛出异常;而Runnable接口的run()方法的异常只能在内部消化,不能继续上抛;
class Thread_1 implements Callable<String> {
private int num = 1000;
@Override
public String call() throws Exception {
while (this.num-- > 0) {
System.out.println("num = " + num);
}
return String.valueOf(num);
}
}
@Test
public void test_1() {
Executor executor=Executors.newSingleThreadExecutor();
Callable<String> callable=new Thread_1();
FutureTask<String> task = new FutureTask<>(callable);
executor.execute(task);
try {
System.out.println("task.get() = " + task.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}