1、继承Thread类并重写run方法,调用继承类的start方法开启线程;

2、通过实现Runnable接口,重写run方法,调用线程对象的start方法开启线程;

3、实现Callable接口,实现call方法,并用FutureTask类包装Callable对象开启线程。

package com.test.one;

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

public class ThreadDemo {
    public static void main(String[] args) throws Exception {
//        1、继承Thread类的方式
        new Thread(new MyThread0(), "A").start();

//        2、实现Runnable接口的方式
        new Thread(new MyThread1(), "B").start();
/**
 *  3、实现Callable接口的方式
 *      new MyThread2() 这里表示多线程要执行的任务
 *      new FutureTask<>() 作用是管理多线程运行的结果
 *      new Thread(futureTask, "C").start()启动线程
 */
        FutureTask<Integer> futureTask = new FutureTask<>(new MyThread2());
        new Thread(futureTask, "C").start(); //启动线程
        System.out.println(futureTask.get()); //get 获取返回值
    }
}

class MyThread0 extends Thread {
    public void run() {
        System.out.println(Thread.currentThread().getName() + " in Thread");
    }
}

class MyThread1 implements Runnable {
    public void run() {
        System.out.println(Thread.currentThread().getName() + " in Runnable");
    }
}

class MyThread2 implements Callable<Integer> {
    public Integer call() throws Exception {
        System.out.println(Thread.currentThread().getName() + " in callable");
        return 200;
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.