程序结果不对,帮忙调下。就是两个线程给一个Person一个加血~一个减血。
我想要的结果是Person 失血而亡,但是结果是满血复活...帮忙调下。- class MyTest
- {
- public static void main(String[] args)
- {
- Person p = new Person();
- new Thread(new AddLife(p)).start();
- new Thread(new HurtLife(p)).start();
- }
- }
- class Person
- {
- private int life = 10000;
- /*加血*/
- public void addLife(){
- life+=20;
- System.out.println("Person加了"+20+"的血,现在Life值是:"+life);
- }
- /*减血*/
- public void hurtLife(int x){
- if(x>life){
- /*伤害值如果大于life,
- 则life值直接为0;
- */
- life=0;
- }else{
- life-=x;
- }
- System.out.println("Person受到"+x+"伤害,现在Life值是:"+life);
- }
-
- public int getLife(){//get
- return life;
- }
- }
- class AddLife implements Runnable
- {
- private Person p;
- AddLife(Person p){this.p=p;}
-
- public void run(){
- while(true){
- synchronized(p){
- if(p.getLife()<9000)//如果life值小于9000开始加血
- {
- p.addLife();
- }
- }
- }
- }
- }
- class HurtLife implements Runnable
- {
- private Person p;
- HurtLife(Person p){this.p=p;}
- public void run(){
- while(true){
- synchronized(p){
- if(p.getLife()>0){//大于零开始减血
- p.hurtLife(200);
- }
- else if (p.getLife()==0)//等于零表示挂了,程序退出。
- {
- System.out.println("Person挂了");
- return;
- }
- }
- }
- }
- }
复制代码 |