实现线程的三种方法
实现线程有三种方法:
1.实现Runnable接口
2.实现Callable
3.继承Thread类
实现 Runnable 和 Callable 接口的类只能当做一个可以在线程中运行的任务,不是真正意义上的线程,因此最后还需要通过 Thread 来调用。可以说任务是通过线程驱动从而执行的。
1.实现Runnable接口
class MyRunnable implements Runnable {
public void run() {
System.out.println("注意Runnable接口,没有返回值");
}
}
class Test1 {
public static void main(String[] args) {
MyRunnable instance = new MyRunnable();
Thread thread = new Thread(instance);
thread.start();
}
}
2.实现Callable
class MyCallable implements Callable<String>{
@Override
public String call() throws Exception {
return "注意Callable是泛型类,返回值就是泛型的类型";
}
}
class Test2 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyCallable mc = new MyCallable();
FutureTask<String> ft = new FutureTask<>(mc);
Thread newThread = new Thread(ft);
newThread.start();
System.out.println(ft.get());
}
}
3.继承Thread类
class MyThread extends Thread {
public void run() {
System.out.println("直接继承Thread类,重写run方法");
}
}
class Test3 {
public static void main(String[] args) {
MyThread mt = new MyThread();
mt.start();
}
}