package com.yyj.zxy;
public class SanJunFight {
/**
* 三只部队轮流上战场,每只部队在战场上每一轮只能进行n次攻击;
* 合计攻击300次则停止攻击;
*/
private static int count = 1; //攻击计数器
private static int part = 1; //默认第一支部队先进行第一次攻击
private static int n = 10; //每次攻击多少次
public static void main(String[] args) {
final SanJunFight s = new SanJunFight();
//第一支部队攻击线程;
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < n; i++) {
synchronized (s) {
while(part !=1)
try {
s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
for(int j=0;j<n;j++){
System.out.print("部队:"+part+"进行第"+ count+"次攻击!");
int fightTime = 0;
fightTime = 1000;
System.out.println("攻击"+fightTime/1000+" 秒结束 >>>>> 本次攻击完成" );
count ++;
}
System.out.println();
part = 2; //n次攻击后,由部队2进行下一轮攻击
s.notifyAll(); //唤醒等待攻击的部队;
}
}
}
}).start();
//第2支部队攻击线程;
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < n; i++) {
synchronized (s) {
while(part !=2)
try {
s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
for(int j=0;j<n;j++){
System.out.print("部队:"+part+"进行第"+ count+"次攻击!");
int fightTime = 0;
fightTime = 1000;
System.out.println("攻击"+fightTime/1000+" 秒结束 >>>>> 本次攻击完成" );
count ++;
}
System.out.println();
part = 3; //n次攻击后,由部队3进行下一轮攻击
s.notifyAll(); //唤醒等待攻击的部队;
}
}
}
}).start();
//第3支部队攻击线程;
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < n; i++) {
synchronized (s) {
while(part !=3)
try {
s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
for(int j=0;j<n;j++){
System.out.print("部队:"+part+"进行第"+ count+"次攻击!");
int fightTime = 0;
fightTime = 1000;
System.out.println("攻击"+fightTime/1000+" 秒结束 >>>>> 本次攻击完成" );
count ++;
}
System.out.println();
part = 1; //n次攻击后,由部队1进行下一轮攻击
s.notifyAll(); //唤醒等待攻击的部队;
}
}
}
}).start();
}
}
多线程问题,三个线程轮流进行,每个线程进行n次操作,共执行n*n*3次操作。本代码用三军攻击做演示,通俗易懂。
最新推荐文章于 2024-02-29 17:24:49 发布