JAVA中创建线程的三种方式

1 继承Thread类

重写run方法,使用start()开启线程,如此,就可以同时做多件事情

public class MyThread extends Thread{

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread()+ " " + i);
        }
    }
}

public class Main {

    public static void main(String[] args) {
        MyThread mt = new MyThread();
        mt.start();

        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread()+ " " + i);
        }
    }
}

2 实现Runnable接口

因为java是单继承机制,所以实现接口的方式更常使用。同样需要重写run方法,使用start()开启线程

public class MyThread2 implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread()+ " " + i);
        }
    }
}

public class Main {

    public static void main(String[] args) {

        MyThread2 mt = new MyThread2();
        Thread t = new Thread(mt);
        t.start();

        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread()+ " " + i);
        }
    }
}

3 实现Callable接口

通过此种方式开启的线程,可以存在返回值,主线程可以等待此线程执行完毕之后继续执行,也可以选择兵分两路
重写call()方法

public class MyThread3 implements Callable{
    @Override
    public Integer call() throws Exception {

        int sum = 0;
        for (int i = 0; i < 100; i++) {
            sum+=i;
        }
        return sum;
    }
}

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

public class Main {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        Callablecallable = new MyThread3();
        FutureTasktask = new FutureTask<>(callable);

        new Thread(task).start();
        Integer integer = task.get();
        System.out.println(integer);//输出4590
    }
}