源自:2-4 Java线程-隋唐演义实战开发---军队
没有循环的内容,直接提示战斗结束了怎么回事?
public class ArmyRunnable implements Runnable {
//volatile保证了线程可以正确的读取其他线程写入的值
//可见性 JMM,happens-before原则??????????????????????????
volatile boolean keepRunning;
@Override
public void run() {
while(keepRunning){
//发动五连击
for(int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName()+"攻击对方【"+i+"】次!");
}
//让出处理器时间,让线程们“公平竞争”
Thread.yield();
}
System.out.println(Thread.currentThread().getName()+"战斗结束了!");
}
}
/**
* 军演舞台
*/
public class Stage extends Thread{
@Override
public void run() {
//创建红蓝方攻击的实例
ArmyRunnable redAttack0 = new ArmyRunnable();
ArmyRunnable blueAttack0 = new ArmyRunnable();
//创建线程
Thread redAttack = new Thread(redAttack0,"红方军团");
Thread blueAttack = new Thread(blueAttack0,"蓝方军团");
//启动线程,开始作战
redAttack.start();
blueAttack.start();
//关闭舞台线程,保证军演专心进行
try {
// this.sleep(50);
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
//关闭线程,鸣金收兵
redAttack0.keepRunning=false;
blueAttack0.keepRunning=false;
//保证蓝方运行结束????????????????????????
try {
blueAttack.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//启动舞台,开始观战
new Stage().start();
}
}
提问者:秦家小小神
2017-07-06 00:56