java中实现多线程的方法有哪几种

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhangquan2015/article/details/82808579

实现多线程的方法有三种:

  1. 实现Runnable接口,并实现接口的run()方法
  2. 继承Thread类,重写run方法
  3. 实现Callable接口,重写call()方法

实现Runnable接口,并实现接口的run()方法

(1)自定义类并实现Runnable接口,实现run()方法。
(2)创建Thread对象,用实现Runnable接口的对象作为参数实例化该Thread对象。
(3)调用Thread的start()方法

class MyThread implements Runnable
{
	public void run(){
		System.out.println("线程运行");
	}
}
public class Test{
	public static void main(String[] args){
		MyThread thread=new MyThread();
		Thread t=new Thread(thread);
		t.start();//开启线程
	}
}

继承Thread类,重写run方法

当执行start()方法后,并不是立即执行多线程代码,而是使得该线程变为可运行态,什么运行多线程代码由操作系统决定。

class MyThread extends Thread{
	public void run(){
		System.out.println("线程运行");
	}
}
public class Test{
	public static void main(String[] args){
		MyThread thread=new MyThread();
		thread.start();//开启线程
	}
}

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

Callable对象属于Executor框架中的功能类,Callable与Runnable接口类似,但是提供了比Runnable更强大的功能:

  1. Callable可以在任务结束后提供一个返回值,Runnable无法提供这个功能。
  2. Callable中的call()方法可以抛出异常,而Runnable的run()方法不能抛出异常。
  3. 运行Callable可以拿到一个Future对象,Future对象表示异步计算的结果。可以使用Future来监视目标线程调用call()方法的使用情况,当调用Future的get()方法以获取结果是,当前线程就会阻塞,直到call()方法结束返回结果为止。
import java.util.concurrent.*;
public class CallableAndFuture{
	//创建线程
	public static class CallableTest implements Callable<String>{
		public String call() throws Exception{
			return "Hello World";
		}
	}
	public static void main(String[] args){
		ExecutorService threadPool=Executors.newSingleThreadExecutor();
		//启动线程
		Future<String> future=threadPool.submit(new CallableTest());
		try{
			System.out.println("等待线程执行完成");
			System.out.println(future.get());//等待线程结束,并获取返回结果
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
}

输出结果为:

等待线程执行完成
Hello World!

以上三种方式中,前两种方式线程执行完之后没有返回值,第三种有。一般推荐实现Runnable接口的方式,原因如下:Thread类定义了多种方法可以被派生类使用或重写,但是只有run方法是必须被重写的,在run方法中实现这个线程的主要功能。所以没有必要继承Thread,去修改其他方法。

猜你喜欢

转载自blog.csdn.net/zhangquan2015/article/details/82808579