package com.imooc.concurrent.base; public class ArmyRunnable implements Runnable { //volatile保证了线程可以正确读取其他线程写入的值 volatile Boolean keepRunning = true; @Override public void run() { while(keepRunning){ for(int i=0 ; i<5 ; i++){ System.out.println(Thread.currentThread().getName()+"进攻对方"+(i+1)+"次"); //缓冲,释放内存,给予士兵休息的时间 Thread.yield(); } } System.out.println(Thread.currentThread().getName()+"结束了攻击"); } }
package com.imooc.concurrent.base; public class Stage extends Thread { public void run(){ ArmyRunnable armyTaskOfSuiDynasty = new ArmyRunnable(); ArmyRunnable armyTaskOfRevolt = new ArmyRunnable(); //使用runnable接口创建线程 Thread armyOfsuiDynasty = new Thread(armyTaskOfSuiDynasty,"隋军"); Thread armyOfRevolt = new Thread(armyTaskOfRevolt,"农民起义军"); //启动线程,开始作战 armyOfsuiDynasty.start(); armyOfRevolt.start(); try { //舞台线程休眠,专心观看厮杀 Thread.sleep(50); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } armyTaskOfSuiDynasty.keepRunning = false; armyTaskOfRevolt.keepRunning = false; try { armyOfRevolt.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) { new Stage().start(); } }
是怎么结束的,因为while是一个无限循环,代码是怎么运行到
armyTaskOfSuiDynasty.keepRunning = false; armyTaskOfRevolt.keepRunning = false;
这里的,可能我表达的意思不清楚,就是说这个while循环是怎么停止的
慕粉4075985
慕的地6079101
car
慕粉4075985
相关分类