本文主要是介绍创建线程的三种方式-(继承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 {@Overridepublic void run() {System.out.println("Thread Body, extends Thread class");}}
class MyThread2 implements Runnable{@Overridepublic 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
这篇关于创建线程的三种方式-(继承Threads,实现Runnable接口,实现Callable接口)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!