首页 > 解决方案 > Java 线程实现

问题描述

下面是我的示例实现代码,其中没有正确线程运行的代码比使用正确线程实现运行的代码花费更少的时间,请告知我犯了什么错误或代码中的问题

   @Override
   public Integer timeTakenWithoutThreading() {
       System.out.println("StartTime" + new Date());
       Date startDate = new Date();
       int value = 1000000;
       int value2 = 2000000;
       for (int i = 0; i <= value; i++) {
           System.out.println("Value 1" + i);
       }
       for (int i = 0; i <= value2; i++) {
           System.out.println("Value 2" + i);
       }
       System.out.println("StartTime" + startDate);
       System.out.println("endTime" + new Date());
       return null;
   }

   @Override
   public String timeTakenWithThreading() {
       Date start = new Date();
       Date firstThread = new Date();
       threadPoolExecutorService.execute(new Runnable() {
           final int value = 1000000;

           @Override
           public void run() {
               for (int i = 0; i <= value; i++) {
                   System.out.println("Thread 1 Value" + i);
               }

           }
       });

       threadPoolExecutorService.execute(new Runnable() {
           final int value2 = 2000000;

           @Override
           public void run() {
               for (int i = 0; i <= value2; i++) {
                   System.out.println("Thread 2 Value" + i);
               }
               System.out.println("Start Date" + start);
               System.out.println("End Date" + new Date());
           }
       });

       return "You Will Get Response So Soon But Thread Will Execute At the Background";
   }
}```

标签: javamultithreadingexecutorservice

解决方案


即使没有开始并行执行,您也可以计算开始时间。所以时间测量实际上是错误的。您应该在 Runnable 中初始化开始时间。

例如:

       
       threadPoolExecutorService.execute(new Runnable() {
           
           final int value = 1000000;

           @Override
           public void run() {
               // time started.
               Date firstThread = new Date();
               System.out.println("First thread started at" + firstThread);
               for (int i = 0; i <= value; i++) {
                   System.out.println("Thread 1 Value" + i);
               }
               // time ended.
               System.out.println("First thread ended at" + new Date());
           }
       });

也将此应用于第二个线程。您会看到两个线程并行运行。结合起来,它比非线程花费的时间更少。


推荐阅读