春招修仙系列 —— 创建线程的方法

概述:

在Java中创建线程有三种方法:

1 继承Thread类:

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

  @Override
  public void run() {
    System.out.println("start::");
  }
}

结果:
start::

2 实现Runnable接口:

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

class MyThread implements Runnable {

  @Override
  public void run() {
    System.out.println("start::");
  }
}

结果:
start::

3 实现Callable接口:

注:使用Callable的实现类可以FutureTask(Future的实现类)来获取其返回值。

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Solution {
  public static void main(String[] args) throws ExecutionException, InterruptedException {
    FutureTask ft = new FutureTask(new MyThread());
    new Thread(ft).start();
    System.out.println(ft.get());
  }
}

class MyThread implements Callable {

  @Override
  public String call() {
    return "start::";
  }
}

猜你喜欢

转载自blog.csdn.net/Kirito19970409/article/details/86566062