如何在Java中将列表除以奇数

时间:2018-10-21 01:05:45

标签: multithreading

我正在学习线程概念,其中需要根据线程数将列表分开。当线程数为偶数时,以下代码可以正常工作。但是,当列表大小为4且“线程数” = 3时,它不起作用,因为线程仅迭代3次,但列表大小为4(4/3 = 1)。无论如何,在分隔列表中有修改吗?

 System.out.println("Enter number of notification:");
        int numberOfMsg = Integer.parseInt(reader.readLine());
        List<String> notification = new ArrayList<String>();
        for(int i=0;i<numberOfMsg;i++) {

            String line = reader.readLine();
            notification.add(line);
        }

        System.out.println("Enter number of threads:");
        int numberOfThreads = Integer.parseInt(reader.readLine());      
        Thread[] threads = new Thread[numberOfThreads];

        int size = notification.size();
        int listsize = size/numberOfThreads;
        int reminder = size%numberOfThreads;
        List<String> tempList = new ArrayList<String>();
        tempList = notification.subList(0, listsize);
        int count = listsize;
        NotificationThread t1 = null;
        for(int i=0;i<threads.length;i++)
        {
            if(listsize <= size) {
            t1 = new NotificationThread();
            Thread thread = new Thread(t1);

            t1.setNotification(tempList);
            thread.start();
            thread.join();
            if(listsize < size)
            {
            tempList = notification.subList(listsize, listsize+count);

            listsize = listsize+count;
            }
            }

        }

0 个答案:

没有答案