遍历集合中的元素,每次N个

public static void main(String[] args) {
List<Integer> list = Arrays.asList(0,1,2,3,4,5,6,7,8,9,10,11);
int c = 3;
for(int i=0; ;i+=c) {
if(list.size() >= i + c) {
System.out.println(list.subList(i, i+c));
}else {
if(i!=list.size()) {
System.out.println(list.subList(i, list.size()));
}
break;
}

}

System.out.println("end");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Java代码实现: ```java import java.util.ArrayList; import java.util.List; public class ThreadDemo { public static void main(String[] args) { int n = (int)(Math.random() * 10) + 1; // 生成1~10的随机整数 List<Thread> threads = new ArrayList<>(); // 创建n个子线程对象并添加到集合 for (int i = 0; i < n; i++) { Thread thread = new Thread(() -> { String threadName = Thread.currentThread().getName(); synchronized (threads) { threads.add(Thread.currentThread()); System.out.println(threadName + " added to collection."); threads.notifyAll(); } }); thread.start(); } // 等待所有线程的名称都添加到集合 synchronized (threads) { while (threads.size() < n) { try { threads.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } // 遍历集合打印每个线程的名称 System.out.println("All thread names:"); for (Thread thread : threads) { System.out.println(thread.getName()); } } } ``` 在上述代码,我们首先生成了一个1~10的随机整数n,并创建了一个空的线程集合threads。然后,我们循环n次,每次创建一个新的子线程对象,并将其启动。在子线程,我们获取当前线程的名称,并使用synchronized关键字将其添加到线程集合。在添加完毕后,我们通知所有等待线程。 接下来,我们使用synchronized关键字等待所有线程的名称都添加到集合。在等待期间,我们使用wait()方法使当前线程进入等待状态,直到其他线程调用notifyAll()方法唤醒它。最后,我们遍历线程集合,打印每个线程的名称。 注意,我们使用了线程同步机制来确保线程集合的线程安全性。如果不加同步,多个线程可能会同时修改线程集合,导致集合的线程数量不正确或出现线程安全问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值