启动 sj1 nm1 两个进程后,什么时候会修改keep值为false,是随机的吗
public class JunDui implements Runnable{
//volatile保证了线程可以正确的访问其他线程写入的值
volatile boolean keep = true;
@Override
public void run() {
// TODO Auto-generated method stub
while (keep ) {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()
+"发动了"+(i+1)+"次攻击");
//让出了处理器时间
Thread.yield();
}
System.out.println(Thread.currentThread().getName()
+"结束了攻击");
}
}
}
public class Stage extends Thread {
//舞台
@Override
public void run() {
// TODO Auto-generated method stub
JunDui sj = new JunDui();
JunDui nm = new JunDui();
Thread sj1 = new Thread(sj,"隋军");
Thread nm1 = new Thread(nm,"农民起义军");
//启动进程
sj1.start();
nm1.start();
//舞台进程休眠
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sj.keep = false;
nm.keep = false;
try {
sj1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
botao555
相关分类