public class TheTwo implements Runnable {
static int a = 0;
static int b = 0;
static boolean loop = true;
public static void main(String[] args) {
Thread thread1 = new Thread(new TheTwo(), "A队");
Thread thread2 = new Thread(new TheTwo(), "B队");
thread1.start();
thread2.start();
System.out.println("中场休息中-!");
//让main方法这个线程睡眠一会,否则可能直接执行toJudge方法,结果是此时刻的a,b
//而不是Thread1和Threa2线程结束后的a,b
try{
Thread.sleep(5000);
}catch(InterruptedException e){
e.printStackTrace();
}
toJudge(a, b);
}
//比较两个队伍本局胜负
static void toJudge(int num1, int num2) {
if (num1 > num2) {
System.out.println("A队获胜");
}
if (num1 == num2) {
System.out.println("B队获胜");
}
if (num1 < num2) {
System.out.println("两队平局");
}
}
//用来比赛之后中场休息暂停(程序睡眠1秒)
static void toSleep() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//当作比赛时间
static int time = 15;
@Override
public void run() {
synchronized (new Object()) {
toSleep();
while (loop) {
time--;
if (time == 1) {
loop = false;
}
if (Thread.currentThread().getName().equals("A队")) {
a++;
System.out.println("A队得1分,现得" + a + "分");
}
if (Thread.currentThread().getName().equals("B队")) {
b++;
System.out.println("B队得1分,现得" + b + "分");
}
}
}
}
}
//当作比赛时间
static int time = 15;
@Override
public void run() {
synchronized (new Object()) {
toSleep();
while (loop) {
time--;
if (time == 1) {
loop = false;
}
if (Thread.currentThread().getName().equals("A队")) {
a++;
System.out.println("A队得1分,现得" + a + "分");
}
if (Thread.currentThread().getName().equals("B队")) {
b++;
System.out.println("B队得1分,现得" + b + "分");
}
}
}
}