package com.yyj.zxy;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class SanJunFight1 {
/**
* 三只部队轮流上战场,每只部队在战场上每一轮只能进行10次攻击;
* 合计攻击300次则停止攻击;
*/
private static int count = 1; //攻击计数器
private static int part = 1; //默认第一支部队先进行第一次攻击
private static int n = 10;
private static ReentrantLock lock = new ReentrantLock();
private static Condition con1 = lock.newCondition();
private static Condition con2 = lock.newCondition();
private static Condition con3 = lock.newCondition();
public static void main(String[] args) {
//第一支部队攻击线程;
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < n; i++) {
lock.lock();
while(part !=1)
try {
con1.await();
} 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进行下一轮攻击
con2.signal(); //唤醒等待攻击的部队;
}
}
}).start();
//第2支部队攻击线程;
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < n; i++) {
lock.lock();
while(part !=2)
try {
con2.await();
} 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; //5次攻击后,由部队3进行下一轮攻击
con3.signal(); //唤醒等待攻击的部队;
}
}
}).start();
//第3支部队攻击线程;
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < n; i++) {
lock.lock();
while(part !=3)
try {
con3.await();
} 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; //5次攻击后,由部队1进行下一轮攻击
con1.signal(); //唤醒等待攻击的部队;
}
}
}).start();
}
}
采用JDK并发包提供的Lock, Condition等类的相关方法控制多线程.
最新推荐文章于 2022-02-13 18:13:04 发布