JAVA多线程实现的三种方式


JAVA多线程实现方式主要有三种: 继承Thread类实现Runnable接口使用ExecutorService、Callable、Future实现有返回结果的多线程。其中前两种方式线程执行完后都没有返回值,只有最后一种是带返回值的。

继承Thread类实现多线程

继承Thread类的方法尽管被我列为一种多线程实现方式,但Thread本质上也是实现了Runnable接口的一个实例,它代表一个线程的实例,并且,启动线程的唯一方法就是通过Thread类的start()实例方法。start()方法是一个native方法,它将启动一个新线程,并执行run()方法。这种方式实现多线程很简单,通过自己的类直接extend Thread,并复写run()方法,就可以启动新线程并执行自己定义的run()方法。例如:

public class MyThread extends Thread {  
  public void run() {  
   System.out.println("MyThread.run()");  
  }  
}  

在合适的地方启动线程如下:

MyThread myThread1 = new MyThread();  
MyThread myThread2 = new MyThread();  
myThread1.start();  
myThread2.start();  

在这里插入图片描述

实现Runnable接口方式实现多线程

(Thread本质上也是实现了Runnable接口的一个实例)
如果自己的类已经extends另一个类,就无法直接extends Thread(java类的单继承,接口可以多继承),此时,必须实现一个Runnable接口,如下:

public class MyThread extends OtherClass implements Runnable {  
  public void run() {  
   System.out.println("MyThread.run()");  
  }  
}  

为了启动MyThread,需要首先实例化一个Thread,并传入自己的MyThread实例:

MyThread myThread = new MyThread();  
Thread thread = new Thread(myThread);  
thread.start();  

事实上,当传入一个Runnable target参数给Thread后,Thread的run()方法就会调用target.run(),参考JDK源代码(Thread的run方法的实现):

public void run() {  
  if (target != null) {  
   target.run();  
  }  
}  

区别

继承Thread类实现Runnable接口
实现子类继承Thread类具备多线程能力实现接口Runnable具有多线程能力
启动启动线程:子类对象.start()启动线程:目标对象+Thread对象.start()
推荐不建议使用:避免OOP单继承局限性推荐使用:避免单继承局限性,灵活方便,方便同一个对象被多个线程使用

在这里插入图片描述

ExecutorService/Callable/Future实现有返回结果的多线程

步骤

1.实现Callable接口,需要返回值类型;
2.重写call方法,需要抛出异常;
3.创建目标对象;
4.创建执行服务:ExecutorService ser = Executors.newFixedThreadPool(1);
5.提交执行:Future result = ser.submit(t1);
6.获取结果:boolean r1 = result.get();
7.关闭服务:ser.shutdownNow();

概念

ExecutorService、Callable、Future这个对象实际上都是属于Executor框架中的功能类。可返回值的任务必须实现Callable接口,无返回值的任务必须Runnable接口。执行Callable任务后,可以获取一个Future的对象,在该对象上调用get就可以获取到Callable任务返回的Object了,再结合线程池接口ExecutorService就可以实现传说中有返回结果的多线程了。下面提供了一个完整的有返回结果的多线程测试例子:

import java.util.concurrent.*;  
import java.util.Date;  
import java.util.List;  
import java.util.ArrayList;  
  
/** 
* 有返回值的线程 
*/  
@SuppressWarnings("unchecked")  
public class Test {  
public static void main(String[] args) throws ExecutionException,  
    InterruptedException {  
   System.out.println("----程序开始运行----");  
   Date date1 = new Date();  
  
   int taskSize = 5;  
   // 创建一个线程池  
   ExecutorService pool =      Executors.newFixedThreadPool(taskSize);  
   // 创建多个有返回值的任务  
   List<Future> list = new ArrayList<Future>();  
   for (int i = 0; i < taskSize; i++) {  
    Callable c = new MyCallable(i + " ");  
    // 执行任务并获取Future对象  
    Future f = pool.submit(c);  
    //call方法的返回结果输出 f.get().toString()
    // System.out.println(">>>" + f.get().toString());  
    list.add(f);  
   }  
   // 关闭线程池  
   pool.shutdown();  
  
   // 获取所有并发任务的运行结果  
   for (Future f : list) {  
    // 从Future对象上获取任务的返回值,并输出到控制台  
    System.out.println(">>>" + f.get().toString());  
   }  
  
   Date date2 = new Date();  
   System.out.println("----程序结束运行----,程序运行时间【"  
     + (date2.getTime() - date1.getTime()) + "毫秒】");  
}  
}  
  
class MyCallable implements Callable<Object> {  
private String taskNum;  
  
MyCallable(String taskNum) {  
   this.taskNum = taskNum;  
}  
  
public Object call() throws Exception {  
   System.out.println(">>>" + taskNum + "任务启动");  
   Date dateTmp1 = new Date();  
   Thread.sleep(1000);  
   Date dateTmp2 = new Date();  
   long time = dateTmp2.getTime() - dateTmp1.getTime();  
   System.out.println(">>>" + taskNum + "任务终止");  
   return taskNum + "任务返回运行结果,当前任务时间【" + time + "毫秒】";  
  }  
}  

运行结果
这里写图片描述

代码说明:
上述代码中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()方法,会阻塞直到计算完成。

实例(可忽略)

public List<Integer> setShopType(List<Integer> shopIDs, int bizID, int shopType, int operatorID) {
        //1.根据shopIds找到相应的轮转组Ids.
        //2.根据轮转组Id找到本轮转组下面的所有shopId
        for(Integer shopId:shopIDs){
            Response res = rotateService.initRotateGroupWithoutBizValidate(shopId,bizID);
            if(!res.isSuccess()){
                throw new ApplicationException(res.getComment());
            }
        }

        List<RotateGroupDTO> rotateGroupDTOs = rotateGroupService.getRotateGroup(bizID, shopIDs);

        //3.更新所有的shopId的type
        List<Integer> rotateGroupIDs = Lists.transform(rotateGroupDTOs, new Function<RotateGroupDTO, Integer>() {
            @Override
            public Integer apply(RotateGroupDTO input) {
                return input.getId();
            }
        });

        //prepare for log
        Map<Integer, List<RotateGroupShopDTO>> rotateGroupShopMap = rotateGroupShopService.getRotateGroupShop(rotateGroupIDs);
        List<RotateGroupShopDTO> rotateGroupShopDTOList = Lists.newArrayList();
        for (Integer rotateGroupId : rotateGroupShopMap.keySet()) {
            rotateGroupShopDTOList.addAll(rotateGroupShopMap.get(rotateGroupId));
        }
        List<Integer> shopIdList = Lists.transform(rotateGroupShopDTOList, new Function<RotateGroupShopDTO, Integer>() {
            @Override
            public Integer apply(RotateGroupShopDTO input) {
                return input.getShopID();
            }
        });
        ShopHistoryModel model = ShopHistoryModel.builder().shopIdList(shopIdList).bizId(bizID).shopHistoryType(SubActionTypeEnum.VIP_MARK.getCode()).build();
        Map<Integer, Integer> oldValue = (Map<Integer, Integer>) bigCustomerProcessor.getData(model);

        //execute
        Response<Boolean> response = rotateService.setRotateGroupBigCustomer(rotateGroupIDs, bizID, shopType);

        //compare and create log
        Map<Integer, Integer> newValue = (Map<Integer, Integer>) bigCustomerProcessor.getData(model);
        if (response.isSuccess()) {
            bigCustomerProcessor.compareAndCreateLog(model, oldValue, newValue,operatorID);
            return null;
        }

        return shopIDs;

    }

    @Override
    public List<Integer> batchSetShopType(List<Integer> shopIDs, final int bizID, final int shopType, final int operatorID) throws Exception {

        //初始化线程池
        String threadSize = LionConfigUtils.getProperty("roc-operation-tools-pc-web.threadSize", "50");
        ExecutorService executorService = Executors.newFixedThreadPool(Integer.parseInt(threadSize));
   //初始化处理失败的集合
 List<Integer> wrongList = Lists.newArrayList();

    //tasks
  List<Callable<List<Integer>>> tasks = Lists.newArrayList();
        String batchSize = LionConfigUtils.getProperty("roc-operation-tools-pc-web.batchSize", "200");
        List<List<Integer>> batchShopsList = Lists.partition(shopIDs, Integer.parseInt(batchSize));

        for (final List<Integer> shopids : batchShopsList) {
            tasks.add(new Callable<List<Integer>>() {
                @Override
                public List<Integer> call() throws Exception {
                    return setShopType(shopids, bizID, shopType, operatorID);
                }
            });
        }

 //futures   时间监控 invokeAll 之前
 Stopwatch stopwatch = Stopwatch.createStarted();

List<Future<List<Integer>>> futures = executorService.invokeAll(tasks);
for (Future<List<Integer>> future : futures) {
        while (true) {
        if (future.isDone() && !future.isCancelled()) {                    if(CollectionUtils.isNotEmpty(future.get())){
        //返回的结果添加进去
            wrongList.addAll(future.get());
                    }
                    break;
                }
            }
        }

  log.info("batchSetShopType cost time:" + stopwatch.elapsed(TimeUnit.MILLISECONDS) + "ms");
    //关闭线程池
     executorService.shutdown();
      return wrongList;
    }

参考:
http://blog.csdn.net/aboy123/article/details/38307539
http://www.iteye.com/topic/366591
http://mars914.iteye.com/blog/1508429
http://www.cnblogs.com/gw811/archive/2012/10/15/2724602.html

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
1. 继承Thread类 Java提供了Thread类,我们可以通过继承Thread类来实现多线程。具体步骤如下: (1)创建一个继承Thread类的子类,并重写run()方法。 (2)在子类中创建一个Thread类的实例对象,并调用start()方法启动线程。 示例代码如下: ``` public class MyThread extends Thread { @Override public void run() { // 线程执行的代码 } } // 创建线程并启动 MyThread myThread = new MyThread(); myThread.start(); ``` 2. 实现Runnable接口 Java中还可以通过实现Runnable接口来实现多线程。具体步骤如下: (1)创建一个实现Runnable接口的类,并实现run()方法。 (2)在类中创建一个Thread类的实例对象,将实现了Runnable接口的类的实例对象作为参数传入Thread的构造方法中。 (3)调用Thread实例对象的start()方法启动线程。 示例代码如下: ``` public class MyRunnable implements Runnable { @Override public void run() { // 线程执行的代码 } } // 创建线程并启动 MyRunnable myRunnable = new MyRunnable(); Thread thread = new Thread(myRunnable); thread.start(); ``` 3. 实现Callable接口 Java中还可以通过实现Callable接口来实现多线程。与实现Runnable接口相比,实现Callable接口可以有返回值,并且可以抛出异常。具体步骤如下: (1)创建一个实现Callable接口的类,并实现call()方法。 (2)创建一个ExecutorService线程池对象,调用submit()方法提交Callable类的实例对象。 (3)调用Future类的get()方法获取线程执行结果。 示例代码如下: ``` public class MyCallable implements Callable<Integer> { @Override public Integer call() throws Exception { // 线程执行的代码 return 1; } } // 创建线程池对象 ExecutorService executorService = Executors.newFixedThreadPool(1); // 提交Callable实例对象 MyCallable myCallable = new MyCallable(); Future<Integer> future = executorService.submit(myCallable); // 获取线程执行结果 int result = future.get(); ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值