java模拟孙悟空打闹天宫
看了孙卫琴老师的java逍遥游记后中多线程部分后,也模仿来个孙悟空派他的猴子猴孙打闹天宫的场景:
/** * MoneyPKheaven.java * 2012 * @Version 1.0 */package com.zxr.utils;import java.util.Random;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;/** * 说明: 猴子大闹天宫 * @author 傲世狂少 * Date: 2012-4-14 */public class MoneyPKheaven {class Money{private String name;//名称private String title;//头衔public Money(){}public Money(String name, String title) {this.name = name;this.title = title;ExecutorService pool=Executors.newSingleThreadExecutor();pool.execute(new Runnable(){@Overridepublic void run() {pk();}});}//狂打private void pk(){for(int i=1; i<=10; i++){try {Thread.sleep((new Random().nextInt(10)+1)*1000);//中途小休息随机1000-10000millisSystem.out.println(title+": "+name+"--打死了第"+i+"个天兵");} catch (InterruptedException e) {e.printStackTrace();}}}}/** * 功能: 主方法入口 * Date: 2012-4-14 * @author: 傲世狂少 */public static void main(String[] args) {//派1代2代3代上阵new MoneyPKheaven().new Money("小屁猴1","斗战1代");new MoneyPKheaven().new Money("小屁猴2","斗战2代");new MoneyPKheaven().new Money("小屁猴3","斗战3代");}}?对多线程不熟,如有不妥或错误之处,还请多多指正,以使自身不断提高,在此不胜感激!