java中实现多线程的方式

2023-06-03  本文已影响0人  小院看客

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、线程池方式

上一篇下一篇

猜你喜欢

热点阅读