多线程学习(4):三种实现Java多线程的方法:Thread、Callable和Runable 的比较与区别

版权声明: https://blog.csdn.net/qq_29166327/article/details/82931202

2018年10月03日

目录

前言

1、继承Thread类

2、实现Runnable接口,实现run()方法

3、实现Callable接口,重写call()方法


前言

JVM允许应用程序并发执行多线程:最常用的是两个方法:(1)基础Thread类,重写run()方法;(2)或实现Runnable 接口,实现接口的run()方法;(3)另外一种方法是:实现callable 接口,重写call()方法。

1、继承Thread类

启动线程的唯一方法就是通过Thread类的start()方法。start()是native方法,调用可以使得该线程变为可允许态(Runnable),而什么时候执行多线程代码,则是由操作系统决定。

package test3ThreadWays;

public class testThread {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MyThread myThread = new MyThread();
		myThread.start(); //开启了线程,抢占cpu资源
	}

}

class MyThread extends Thread{
	public void run(){
		System.out.println("Thread body 。。"); //任务:线程的函数体
	}	
}

console:

Thread body 。。

2、实现Runnable接口,实现run()方法

使用Runnable接口,需要创建Thread对象,用于实现Runnable接口的对象作为参数实例化该Thread对象。

package test3ThreadWays;

public class testRunnable {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		myRunnable myThread = new myRunnable(); //任务
		Thread thread = new Thread(myThread); //线程
		thread.start();
	}

}

class myRunnable implements Runnable{

	@Override
	public void run() {
		// TODO Auto-generated method stub
		System.out.println("Runnable body..");
	}
	
}

console:

Runnable body..

3、实现Callable接口,重写call()方法

区别:1)任务结束后提供一个返回值,Runnable的run()无法提供该功能;

2)call()可以抛出异常,Runnable的run()无法抛出异常;

3)Callable可以拿到Future对象,表示异步计算的结果,它提供了get()方法【检查计算是否完成】,获取结果;但是当前线程会阻塞;

package test3ThreadWays;

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

public class testCallable {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ExecutorService threadPool = Executors.newSingleThreadExecutor();
		
		//启动线程
		Future<String> future = threadPool.submit(new myCallable());
		
		try{
			System.out.println("waiting the thread to finish,,,");
			System.out.println("获取监听线程返回值: "+future.get()); //使用Future监视目标线程调用call()方法的情况,当前的线程会一直阻塞,直到call()方法结束返回结果。
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}

}
/**
 * callable 比 runnable 强大的地方是:可以返回结果值
 * @return String
 * @others:接口是 Executor 框架的功能类;
 * */
class myCallable implements Callable<String>{

	@Override
	public String call() throws Exception {
		System.out.println("callable body...");
		Thread.sleep(2000);
		return "Hello World!!";
	}
	
}

console:

waiting the thread to finish,,,
callable body...
获取监听线程返回值: Hello World!!

猜你喜欢

转载自blog.csdn.net/qq_29166327/article/details/82931202