0.区别
继承Thread类 | 实现Runnable接口 | 实现Callable接口 |
---|---|---|
优点:编写简单,如果需要访问当前线程,无需使用**Thread.currentThread()**方法,直接使用this,即可获得当前线程 | 优点:线程类只是实现了Runable接口,还可以继承其他的类。在这种方式下,可以多个线程共享同一个目标对象,所以非常适合多个相同线程来处理同一份资源的情况。 | 优点:可以接收返回值 |
缺点:继承了Thread类,所以不能再继承其他的父类。 | 缺点:编程稍微复杂,如果需要访问当前线程,必须使用 Thread.currentThread() 方法。 | \ |
Runnable | Callable |
---|---|
Runnable规定必须重写的方法是run() | Callable规定的方法是call() |
不能返回值 | 可返回值 |
run方法不可以抛出异常 | call方法可以抛出异常 |
\ | 运行Callable任务可以拿到一个Future对象,通过Future对象可以了解任务执行情况,可取消任务的执行,还可获取执行结果。 |
1.继承Thread类
输出:继承Thread类,当前线程Name:我是 Thread
public class Main {
public static void main(String[] args) {
Thread t1 = new Test();
t1.setName("我是 Thread");
t1.start();
}
}
class Test extends Thread{
@Override
public void run() {
System.out.println("继承Thread类,当前线程Name:"+this.getName());
}
}
1.5.临时实现Thread类
输出:临时实现Thread类,当前线程Name:我是 临时实现Thread类
public class Main {
public static void main(String[] args) {
Test test = new Test();
Thread t = new Thread("我是 临时实现Thread类"){
public void run(){
test.Dog();
}
};
t.start();
}
}
class Test{
public void Dog(){
System.out.println("临时实现Thread类,当前线程Name:"+Thread.currentThread().getName());
}
}
2.实现Runnable接口
输出:Runnable接口,+线程Name:我是 Runnable
public class Main {
public static void main(String[] args) {
TestRun testRun = new TestRun();
Thread t = new Thread(testRun,"我是 Runnable");
t.start();
}
}
class TestRun implements Runnable{
@Override
public void run() {
System.out.println("Runnable接口,+线程Name:"+ Thread.currentThread().getName());
Dog();
}
public String Dog(){
return "dog";
}
}
3.实现Callable接口
Callable接口,+线程Name:我是 Callable
Callable 返回值是 dog
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
TestCall testCall = new TestCall();
FutureTask task = new FutureTask(testCall);
Thread t = new Thread(task,"我是 Callable");
t.start();
System.out.println(task.get());
}
}
class TestCall implements Callable {
@Override
public Object call() throws Exception {
System.out.println("Callable接口,+线程Name:"+ Thread.currentThread().getName());
return Dog();
}
public String Dog(){
return "Callable 返回值是 dog";
}
}