以下是代码
CountdownLatch是一个同步工具类,它可以使得等待几个线程一起执行完毕后,再开始执行后面的程序。
package com.test.thread01;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
// 程序开启入口
public class GameStart {
public static void main(String args[]) {
ExecutorService es = Executors.newFixedThreadPool(10);
final CountDownLatch latch = new CountDownLatch(10);
for (int i = 0; i < 10; i++) {
Prole p = RoleFactory.createRole(i);
RoleInitTask<Prole> task = new RoleInitTask<Prole>(latch, p);
es.submit(task);
}
try {
latch.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("所有玩家都到齐");
}
}
英雄初始化
public class RoleInitTask<T extends Prole> implements Runnable {
private final CountDownLatch latch;
private T t;
public RoleInitTask(CountDownLatch latch, T t) {
this.latch = latch;
this.t = t;
}
// 任务开始准备
public void run() {
t.init();// 初始化等待
latch.countDown();
}
}
角色
public abstract class Prole {
private int hp;
private String name;
public Prole(int hp, String name) {
this.hp = hp;
this.name = name;
}
public abstract int decrOther(int rand);
public abstract void init();
public int getHp() {
return hp;
}
public String getName() {
return name;
}
}
package com.test.thread01;
import java.util.Random;
public class Rrole extends Prole {
public Rrole(int hp, String name) {
super(hp, name);
}
@Override
public int decrOther(int rand) {
Random r = new Random();
return r.nextInt(10);
}
@Override
public void init() {
Random r = new Random();
int sleep = 200+ r.nextInt(2000);
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(this.getName() + " 初始化完成。");
}
}
角色工厂
package com.test.thread01;
import java.util.Random;
public class RoleFactory {
private RoleFactory() {
}
public static Prole createRole(int i) {
Random r = new Random();
int hp = 100 + r.nextInt(20);
return new Rrole(hp, "name" + i);
}
}
git地址