0

我遇到了多线程程序的问题。

我需要模拟很多人试图同时预订同一个航班,不使用锁。

所以我做了一个 ExecutorService 并用它来池线程,这样我就可以同时进行许多尝试。

但问题是,程序在打印出所有结果之前就到达了终点,它只是坐在那里并永远运行。我试图进入所有其他使用数据库连接的类,并简单地手动关闭它们。没运气。

package dbassignment4;

   import java.util.ArrayList;
   import java.util.List;
   import java.util.concurrent.ExecutionException;
   import java.util.concurrent.ExecutorService;
   import java.util.concurrent.Future;
   import java.util.concurrent.LinkedBlockingQueue;
   import java.util.concurrent.RejectedExecutionException;
   import java.util.concurrent.ThreadPoolExecutor;
   import java.util.concurrent.TimeUnit;

   /**
    *
    * @author Vipar
    */
   public class Master{

   private static final int POOL_SIZE = 50;
   public static boolean planeIsBooked = false;
   /**
    * @param args the command line arguments
    */
   public static void main(String[] args) {

       int success = 0;
       int seatNotReserved = 0;
       int seatNotReservedByCustomerID = 0;
       int reservationTimeout = 0;
       int seatIsOccupied = 0;
       int misc = 0;

       HelperClass.clearAllBookings("CR9");
       Thread t = new Thread(new DBMonitor("CR9"));
       long start = System.nanoTime();
       //HelperClass.clearAllBookings("CR9");
       ExecutorService pool = new ThreadPoolExecutor(
               POOL_SIZE, POOL_SIZE,
               0L,
               TimeUnit.MILLISECONDS,
               new LinkedBlockingQueue<Runnable>(POOL_SIZE));
       int threadsStarted = 0;
       List<Future<Integer>> results = new ArrayList<>();
       long id = 1;
       t.start();
       while(planeIsBooked == false) {
           try {
           Future<Integer> submit = pool.submit(new UserThread(id));
           results.add(submit);
           } catch (RejectedExecutionException ex) {
               misc++;
               continue;
           }
           threadsStarted++;
           id++;
       }
       pool.shutdownNow();

       int count = 0;
       for(Future<Integer> i : results) {
           try {
               switch(i.get()) {
                   case 0:
                       // Success
                       success++;
                       break;
                   case -1:
                       // Seat is not Reserved
                       seatNotReserved++;
                       break;
                   case -2:
                       // Seat is not Reserved by Customer ID
                       seatNotReservedByCustomerID++;
                       break;
                   case -3:
                       // Reservation Timeout
                       reservationTimeout++;
                       break;
                   case -4:
                       // Seat is occupied
                       seatIsOccupied++;
                       break;
                   default:
                       misc++;
                       // Everything else fails
                       break;
               }
           } catch (ExecutionException | InterruptedException ex) {
               misc++;
           }
           count++;
           System.out.println("Processed Future Objects: " + count);
           // HERE IS WHERE IT LOOPS
       }

以下是它不会立即执行的其余代码:

long end = System.nanoTime();
long time = end - start;
System.out.println("Threads Started: " + threadsStarted);
System.out.println("Successful Bookings: " + success);
System.out.println("Seat Not Reserved when trying to book: " + seatNotReserved);
System.out.println("Reservations that Timed out: " + reservationTimeout);
System.out.println("Reserved by another ID when trying to book: " + seatNotReservedByCustomerID);
System.out.println("Bookings that were occupied: " + seatIsOccupied);
System.out.println("Misc Errors: " + misc);
System.out.println("Execution Time (Seconds): " + (double) (time / 1000000000));
}
}

你能发现问题吗?我在代码停止运行的地方添加了注释。

4

4 回答 4

0

planeIsBooked成为时true,看起来你的 planeIsBooked 永远不会true在 while 循环中被初始化。因此,请确保您的循环不是无限的。

于 2014-05-03T19:50:14.173 回答
0

第一件事while(planeIsBooked == false)总是评估为真,因为

planeIsBooked = false always , nowhere its initialized to true. 

那么你的while循环条件怎么会变成假并出来呢?

设置在 while 循环内某处planeIsBooked = true以退出 while 循环。

于 2014-05-03T19:53:43.980 回答
0

几件事:

首先,在您致电之后pool.shutdownNow(); - 您将继续尝试立即获取结果。调用 shutDownNow() 不会阻塞,也不是池已停止的明确指示。为此-您应该调用pool.awaitTermination().

其次,不清楚您的评论是什么意思-

// 这里是循环的地方

这是一个循环 - 并查看循环 - 如果在 switch case 中抛出异常 - 那么它将进入 catch - 忽略它并循环。你检查异常了吗?

于 2014-05-03T19:54:03.740 回答
0

仔细阅读这个答案,了解为什么应该在多线程环境中将静态变量声明为 volatile。

即使您的静态变量是易变的,以下几行也是危险的

while(planeIsBooked == false) {
        Future<Integer> submit = pool.submit(new UserThread(id));
   }

考虑您的预订航班平均需要 2 秒。你有大约 300 个座位(假设)。您的 planeIsBooked 字段将在 600 秒后变为真(如果它在单线程中运行)。使用 50 个大小的池,它将在 12 秒内运行。

根据上述假设,您的循环将运行 12 秒。现在,想想提交请求语句执行了多少次?我次。即使您只有 300 个席位,您也可能会在 12 秒内提供大约更多的最低百万请求。

因此,在调用 Shutdown now() 之前考虑一下队列中的作业数。这不是终止循环的正确方法

如果您知道飞行座位的最大尺寸,为什么不在 for 循环中使用它(可能是在 for 循环中外部化参数,而不是变量来保存

于 2014-05-03T20:19:48.237 回答