重游java系列一线程 从装卸工开始
重游java系列一线程 从搬运工开始
java开发已经三年了,总感觉太浮躁。这些天静下心来,对这门语言小深入了一下,特撰写该系列。
本篇内容以模拟现实场景为线索,主要针对java线程的同步以及线程池的应用。
模拟场景:
一家工厂有1000包大米(有编号)放在仓库,最近仓库进水了,老板请了100个农民工,打算搬到外面让太阳晒晒,民工速度有快有慢,工钱根据搬运的大米数量计算,大米随机搬运。
java开发已经三年了,总感觉太浮躁。这些天静下心来,对这门语言小深入了一下,特撰写该系列。
本篇内容以模拟现实场景为线索,主要针对java线程的同步以及线程池的应用。
模拟场景:
一家工厂有1000包大米(有编号)放在仓库,最近仓库进水了,老板请了100个农民工,打算搬到外面让太阳晒晒,民工速度有快有慢,工钱根据搬运的大米数量计算,大米随机搬运。
import java.util.HashMap; import java.util.Iterator; import java.util.Random; import java.util.Vector; public class Test3 { public static void n(String[] args) { Vector<Goods> goodsList = new Vector<Goods>();//进货 GoodFactory factory = new GoodFactory(goodsList);//仓库 for (int i = 0; i < 1000; i++) { Goods goods = new Goods(i); goodsList.add(goods); } //ExecutorService service = Executors.newScheduledThreadPool(10);//如果仓库很小 for (int i = 0; i < 100; i++) { Person person = new Person(factory, i); new Thread(person).start(); //service.execute(person); } //service.shutdown(); while (factory.getGoodsCount() != 0) { } Iterator<Integer> iterator = factory.counter.values().iterator(); int count = 0; while (iterator.hasNext()) { count += iterator.next(); } System.out.println("共搬了" + count + "件商品"); } } /** * 模拟工厂 类 * @author ilikeido * */ class GoodFactory { Vector<Goods> goodsQueue;//商品 HashMap<Person, Integer> counter = new HashMap<Person, Integer>();//统计员 public GoodFactory(Vector<Goods> goodsQueue) { this.goodsQueue = goodsQueue; } /** * 随机搬货 * @param person 工人 * @return */ public synchronized Goods moveRandom(Person person) { int old = goodsQueue.size(); if (old > 0) { int index = 0; try { index = new Random().nextInt(old - 1); } catch (Exception e) { } Goods goods = goodsQueue.get(index); goodsQueue.remove(index); person.say(goods); if (counter.get(person) == null) { counter.put(person, 1); } else { counter.put(person, counter.get(person) + 1); } return goods; } return null; } public int getGoodsCount() { return goodsQueue.size(); } } /** * 工人 * @author ilikeido * */ class Person implements Runnable { GoodFactory factory; public static ThreadLocal<Integer> count = new ThreadLocal<Integer>() { @Override protected Integer initialValue() { return 1; } }; int id; public Person(GoodFactory factory, int id) { this.factory = factory; this.id = id; } /** * 搬货 */ public void move() { factory.moveRandom(this); count.set(count.get().intValue() + 1); } @Override public void run() { while (factory.getGoodsCount() > 0) { move(); count.set(count.get() + 1); try { Thread.sleep(new Random().nextInt(1000)); } catch (InterruptedException e) { e.printStackTrace(); } } } public void say(Goods goods) { System.out.println(this.toString() + "搬运了" + goods.toString() + ",共搬了" + count.get() + "包"); } public String toString() { return "工人" + id; } } /** * 商品 * @author ilikeido * */ class Goods { int gflag; public Goods(int gflag) { this.gflag = gflag; } public String toString() { return "商品编号:" + gflag; } }