java中实现多线程的方式

1、继承Thread类实现

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

  @override
  public void run(){
    System.out.println("hello");
  }
}

重写的是run方法
2、实现Runnable接口

public class MyThread implements Runnable{
  public static void main(String[] args){
    Thread thread = new Thread(new MyThread());
    thread.start();
  }
  public void run(){
    System.out.println("hello");
  }
}

3、实现Callable接口

public class MyThread implements Callable<String>{
  public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<String> futureTask = new FutureTask<>(new MyThread());
        Thread thread = new Thread(futureTask);
        thread.start();
        String result = futureTask.get();
        System.out.println(result);
    }

    @Override
    public String call() throws Exception {
        return "hello";
    }
}

实现call方法,得使用Thread+FutureTask,这种方式支持拿到异步执行任务的结果。
4、线程池方式

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

友情链接更多精彩内容