创建线程的三种方式-(继承Threads,实现Runnable接口,实现Callable接口)

综述

Java使用Thread类代表线程,所有的线程对象都必须是Thread类或其子类的实例。Java可以用三种方式来创建线程,如下所示:

1)继承Thread类创建线程

2)实现Runnable接口创建线程

3)使用Callable和Future创建线程

下面让我们分别来看看这三种创建线程的方法。

demo实例演示

package com.dlut.jeremy;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Main {
    public static void main(String[] args) {
        // 这是通过继承Thread类创建的线程
        MyThread1 mt1 = new MyThread1();
        mt1.start();
        // 这是实现Runnable接口,比上述步骤多一步
        MyThread2 mt2 = new MyThread2();
        Thread t2 = new Thread(mt2);
        t2.start();
        // 这是实现callable接口
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        // 启动线程,并且带返回值的
        Future <String> future = threadPool.submit(new CallableTest());

        try {
            System.out.println("waiting thread to finish");
            System.out.println(future.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}
class MyThread1 extends Thread {

    @Override
    public void run() {
        System.out.println("Thread Body, extends Thread class");
    }

}
class MyThread2 implements Runnable{

    @Override
    public void run() {
        System.out.println("Thread Body, implement Runnable interface");
    }

}

class CallableTest implements Callable <String>{
    public String call() throws Exception{
        return "Hello World";
    }
}


程序运行结果:

Thread Body, extends Thread class
Thread Body, implement Runnable interface
waiting thread to finish
Hello World

猜你喜欢

转载自blog.csdn.net/siying8419/article/details/80874490