class Hero {
private String name;
public int hp = 10;
public Hero(String str) {
this.name = str;
}
public synchronized void recover() {
this.hp += 1;
}
public synchronized void hurt() {
this.hp -= 1;
}
}
public class Test {
public static void main(String[] args) {
Hero garen = new Hero("garen");
// 线程一
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "....");
while (true) {
while (garen.hp == 1) {
continue;
}
try {
Thread.sleep(200);
garen.hurt();
System.out.println(Thread.currentThread().getName() + "..." + "hp down-" + garen.hp);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
// 线程二
new Thread(() -> {
while (true) {
if (garen.hp == 20) {
continue;
}
try {
Thread.sleep(400);
garen.recover();
System.out.println(Thread.currentThread().getName() + "....." + "hp up-" + (garen.hp));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
}
为什么线程一不执行了?是因为没有更新 garen.hp 的值吗?