手撕Java多线程(一)线程创建

线程的三种创建方式

有三种使用线程的方法:

  • 实现 Runnable 接口;
  • 实现 Callable 接口;
  • 继承 Thread 类。

实现Runnable接口和Callable接口的类只能当作一个可以在线程中运行的任务,不是真正意义上的线程,因此最后还需要通过Thread来调用。可以说任务是通过线程驱动从而执行的。

一、实现Runnable接口

需要实现Run方法。

public class MyRunnable implements Runnable {
    public void run() {
        // ...
    }
}
public static void main(String[] args) {
    MyRunnable instance = new MyRunnable();
    Thread thread = new Thread(instance);
    thread.start();
}

二、实现Callable接口

与Runnable相比,Callable可以有返回值,返回值通过FutureTask进行封装。

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类也实现了Runnable接口。

当调用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类开销过大。
posted @ 2022-09-30 15:47  iiiiiiiivan  阅读(29)  评论(0)    收藏  举报