通过Thread.sleep把任务平均分配给线程按顺序执行的小例子
程序员文章站
2024-01-09 16:30:52
...
package com.lj.test.JavaSe4; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.commons.io.FileUtils; public class App { public static void main(String[] args) throws InterruptedException, IOException { for(int i=0;i<100;i++){ FileUtils.writeStringToFile(new File("d:/test.txt"), i+"\r\n", true); } ExecutorService service = Executors.newFixedThreadPool(3); List<String> urls=new ArrayList<String>(); urls=FileUtils.readLines(new File("d:/test.txt")); while(urls.size()!=0){ Hello h=new Hello(urls.get(0)); service.submit(h); urls.remove(0); Thread.sleep(1); } service.shutdown(); } } class Hello implements Runnable { private String str; public Hello(String str) { this.str=str; } @Override public void run() { System.out.println(Thread.currentThread().getName()+"-handle-"+str); } }
只要加入了sleep, 就会按照123的顺序不停的循环调用线程, 而不是每个线程都再抢任务执行。
上一篇: 计算结余数
下一篇: oracle bakup.sh