先打个比方,现实生活中,老板有一车苹果需要搬运,通常情况下,老板为了加快搬运效率,会同事让几个人来搬运;那几个人来搬运,就会涉及到分工钱的事情,比如老板说搬完这一车苹果,我给2k块钱,假如喊了5个人来搬,那怎么分工钱呢,是多劳多得,还是说平均分配,每人400呢?
这两个方式,就是我今天要基于线程池,来进行模拟实现。
公共部分,定义创建线程池线程的名称,实现ThreadFactory的newThread方法
public class SceneThreadFactory implements ThreadFactory { private ThreadGroup threadGroup =null;//线程分组 private String name;//线程组名称 @Override public Thread newThread(Runnable r) { if(threadGroup==null){ threadGroup=new ThreadGroup(name); } Thread thread = new Thread(threadGroup,r); thread.setName(threadGroup.getName()+"-"+nextThreadNum());//每条线程的名称 return thread; } public SceneThreadFactory(String name){ this.name=name; } private static int threadInitNumber; private static synchronized int nextThreadNum() { return threadInitNumber++; } }
1、多劳多得 ,谁搬的多,谁分的钱多
//实现搬苹果的任务
public class TestRunnableExcute implements Runnable { private int allApples = 0; public TestRunnableExcute(int allApples){ this.allApples = allApples; } public synchronized int getApples(){ return this.allApples; } public synchronized void moveApples(int apples){ this.allApples = this.allApples - apples; } @Override public void run() { //开始搬苹果,每次搬运100个苹果 if(getApples() > 0){ moveApples(100); System.out.println(Thread.currentThread().getName() + "取走了100个苹果,还剩下"+this.getApples()+"个苹果!"); } } }
SceneThreadFactory factory = new SceneThreadFactory("搬运苹果");
//初始化5条线程
ExecutorService executorService = Executors.newFixedThreadPool(5,factory);
//10w个苹果,5个人搬,搬完为止
TestRunnableExcute testRunnableExcute = new TestRunnableExcute(100000);
do{
executorService.execute(testRunnableExcute);
}while (testRunnableExcute.getApples() > 0);
//关闭线程池
executorService.shutdown();
2、平均分配,每个人的任务分配一样多,只搬运一定数量的苹果
public class FixedQuantityRunnableExcute implements Runnable { private int allApples = 0; public FixedQuantityRunnableExcute(int allApples){ this.allApples = allApples; } public int getApples(){ return this.allApples; } public void moveApples(int apples){ this.allApples = this.allApples - apples; } @Override public void run() { //开始搬苹果,每次搬运100,直到搬完为止 while(getApples() > 0){ moveApples(100); System.out.println(Thread.currentThread().getName() + "取走了100个苹果,还剩下"+this.getApples()+"个苹果!"); } } }
SceneThreadFactory factory = new SceneThreadFactory("搬运苹果");
//初始化5条线程
ExecutorService executorService = Executors.newFixedThreadPool(5,factory);
//一共100000苹果
int allApples = 100000;
//分五条线程来处理,每人20000个苹果
int avgApples = allApples/5;
//5条线程,平均分配任务
for(int i = 0;i<5;i++){
FixedQuantityRunnableExcute fixedQuantityRunnableExcute = new FixedQuantityRunnableExcute (avgApples);
executorService.execute(fixedQuantityRunnableExcute);
}
//关闭线程池
executorService.shutdown();