Java实现多线程的三种方式

1. 继承Thread类

public class Main {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
}

class MyThread extends Thread{
    public void run(){
        System.out.print("Thread Body");
    }
}

继承Thread后,调用start()方法就是执行类类中的run()方法,这也是启动线程的唯一方法。它是一个native方法,当此方法调用以后并不是马上就执行多线程代码,而是把该线程变为可运行Runnable状态,什么时候执行则由操作系统决定。

2. 实现Runnable接口

public class Main {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        Thread thread = new Thread(myThread);
        thread.start();
}

class MyThread extends otherClass implements Runnable{
    public void run(){
        System.out.print("Thread Body");
    }
}

当类已经继承于别的类而不能继承Thread类时,可以使用实现Runnable接口的方法。但是在这种方法下,要先创建Thread对象,用实现Runnable接口的对象作为参数实例化该Thread对象。

3. 实现Callable接口,重写call()方法

Callable 对象实际属于Executor框架中的功能类,Callable接口和Runnable接口类似,但功能更强大

  • Callable可以在任务结束后提供一个返回值
  • Callable中的call()方法可以抛出异常,Runnable中的run()方法则不可以
  • 运行Callable可以拿到一个Future对象,Future对象表示异步计算的结果。它提供了检查计算是否完成的方法。由于线程属于异步计算模型,所以无法从其他线程中得到方法的返回值,在这种情况下,就可以用Future来监视目标线程调用run()方法的情况,当调用Future的get()方法获取结果的时候,当前线程就会阻塞,直到call()方法结束返回结果。
public class Main {
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        Future<String> future = threadPool.submit(new MyThread());
        try{
            System.out.println("Waiting thread to finish");
            System.out.println(future.get());
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}

class MyThread implements Callable<String>{
    public String call() throws Exception{
        return "Thread Body";
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容