Java多线程实现的四种方式

Java多线程实现的四种方式

1. 继承Thread类,重写run方法
2. 实现Runnable接口,重写run方法
3. 实现Callable和Future接口创建线程
4. 通过线程池创建线程

前面2种都为无返回值,原因为重写run的方法的返回值为void,所以没有办法返回结果。
后面2种都为有返回值,通过Callable接口,就要实现call方法,这个方法有返回值Object,返回的结果可以放在Object中。

第一种:继承Thread类,重写该类的run方法

class MyThread extends Thread{
	private int i=0;
	@Override
	public void run(){
		for(int i=0;i<10;i++){
			System.out.println(Thread.currentThread().getName()+" "+i);
		}
	}
}

通过继承Thread类及重写run方法,定义了一个新的线程类MyThread,在run()中有线程将要完成的任务。

public class ThreadTest{
	public static void main(String[] args){
		for(int i=0;i<10;i++){
			System.out.println(Thread.currentThread().getName()+" "+i);
			if(i==5){
				Thread myThread1 = new MyThread();  //创建一个新线程 myThread1,此线程进入新建状态
				Thread myThread2 = new MyThread();
				myThread1.start();   //此线程进入就绪状态,不一定立即执行,取决于CPU调度时机
				myThread2.start();
			}
		}
	}
} 

第二种:实现Runnable接口,重写run方法

创建Runnable实现类的实例,并以此实例作为Thread类的target来创建Thread对象,该Thread对象才是真正的线程对象。

class MyRunnable implements Runnable{
	private int i = 0;
	@Override 
	public void run(){
		for(int i=0;i<10;i++){
			System.out.println(Thread.currentThread().getName()+" "+i);
		}
	}
}
public class ThreadTest{
	public static void main(){
		for(int i=0;i<10;i++){
			System.out.println(Thread.currentThread().getName()+" "+i);
			if(i == 5){
				Runnable myRunnable = new MyRunnable();  //创建MyRunnable实现类的对象
				Thread thread1 = new Thread(myRunnable);  //将myRunnable作为Thread的target 创建新的线程
				Thread thread2 = new Thread(myRunnable);
				thread1.start();
				thread2.start();
			}
		}
	}
}

第三种:使用Callable和Future接口创建线程。

  1. 创建Callable接口的实现类,并实现Call方法
  2. 创建Callable实现类的实现,使用FutureTask类包装Callable对象,该FutureTask对象封装了Callable对象的Call方法的返回值
  3. 使用FutureTask对象作为Thread对象的target创建并启动线程
  4. 调用FutureTask对象的get()来获取子线程执行结束的返回值
class MyCallable implements Callable<Integer>{
	private int i=0;
	// 与run()方法不同的是,call()方法具有返回值
	@Override
	public Integer call(){
		int sum = 0;
		for( ;i<10;i++){
			System.out.println(Thread.currentThread().getName() +" "+ i);
			sum+=i;
		}
		return sum;
	}
}

public class ThreadTest{
	public static void main(String[] args){
		Callable<Integer> myCallable = new MyCallable();  //创建MyCallable()对象
		FutureTask<Integer> ft = new FutureTask<Integer>(myCallable );  //使用FutureTask来包装MyCallable对象
		for(int i=0;i<10;i++){
			System.out.println(Thread.currentThread().getName() + " "+i);
			if(i == 5){
				Thread thread = new Thread(ft);
				thread.start();    //线程进入到就绪状态
			}
		}
		System.out.println("主线程for循环执行完毕..");
		
		try{
			int sum = ft.get();    //取得新创建的新线程中的call()方法返回的结果
			System.out.println("sum = " + sum);
		}catch(InterruptedException e){
			e.printStackTrace();
		}catch(ExecutionException e){
			e.printStackTrace();
		}
	}
}

在实现Callable接口中,此时不再是run()方法了,而是call()方法,此call()作为线程执行体,还有返回值!
在创建新线程时,通过FutureTask对象来封装MyCallable对象,同时作为了Thread对象的target。

第四种:通过线程池创建线程。

class RunnableThread implements Runnable { 
    @Override 
    public void run() { 
        System.out.println("通过线程池方式创建的线程:" + Thread.currentThread().getName()); 
    } 
} 

public class ThreadDemo05{
	private static int POOL_NUM = 10; //线程池数量 
	public static void main(String[] args) throws InterruptedException { 
		ExecutorService executorService = Executors.newFixedThreadPool(5);
		for(int i=0;i<POOL_NUM;i++){
			RunnableThread thread = new RunnableThread();
			//Thread.sleep(1000); 
			executorService.executor(thread);
		}
		//关闭线程池
		executorService.shutdown();
	}
}
ExecutorService、Callable都是属于Executor框架。
返回结果的线程是在JDK1.5中引入的新特征,还有Future接口也是属于这个框架,有了这种特征得到返回值就很方便了。

通过分析可以知道,它同样也是实现了Callable接口,实现了Call方法,所以有返回值。这也就是正好符合了前面所说的两种分类。

执行Callable任务后,可以获取一个Future的对象,在该对象上调用get就可以获取到Callable任务返回的Object了。
get方法是阻塞的,即:线程无返回结果,get方法会一直等待。

再介绍Executors类:提供了一系列工厂方法用于创建线程池,返回的线程池都实现了ExecutorService接口。

public static ExecutorService newFixedThreadPool(int nThreads)
创建固定数目线程的线程池。

public static ExecutorService newCachedThreadPool()
创建一个可缓存的线程池,调用execute 将重用以前构造的线程(如果线程可用)。
如果现有线程没有可用的,则创建一个新线程并添加到池中。
终止并从缓存中移除那些已有 60 秒钟未被使用的线程。

public static ExecutorService newSingleThreadExecutor()
创建一个单线程化的Executor。

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
创建一个支持定时及周期性的任务执行的线程池,多数情况下可用来替代Timer类。

ExecutoreService提供了submit()方法,传递一个Callable,或Runnable,返回Future。
如果Executor后台线程池还没有完成Callable的计算,这调用返回Future对象的get()方法,会阻塞直到计算完成。

转载:https://www.cnblogs.com/tutubaobao/p/10049903.html

参考:https://www.cnblogs.com/lwbqqyumidi/p/3804883.html
https://blog.csdn.net/u011480603/article/details/75332435/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值