看了孫衛琴老師的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(){
@Override
public void run() {
pk();
}
});
}
//狂打
private void pk(){
for(int i=1; i<=10; i++){
try {
Thread.sleep((new Random().nextInt(10)+1)*1000); //中途小休息隨機1000-10000millis
System.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代");
}
}
對多線程不熟,如有不妥或錯誤之處,還請多多指正,以使自身不斷提高,在此不勝感激!