package Multithreading;import java.util.Random;
import java.util.concurrent.locks.ReentrantLock;public class RunningableDemo implements Runnable {
    private Thread thread;
    private String threadName;
    static LifeValue lifeValue=new LifeValue();
    private Random r=new Random();    RunningableDemo(String name){
        threadName=name;
        System.out.println("Creating "+threadName);
    }    public synchronized int attack(String threadName){        if (lifeValue.getFlag()<=0) return 0;        int kind=r.nextInt(3)+1;
        if(kind==1){
            lifeValue.Attack1();
            System.out.println(threadName+" attact 10");
            System.out.println(threadName+" LifeValue="+lifeValue.getLifeValue());
        }else if (kind==2){
            lifeValue.Attack2();
            System.out.println(threadName+" attact 20");
            System.out.println(threadName+" LifeValue="+lifeValue.getLifeValue());
        }else if (kind==3){
            lifeValue.Attack3();
            System.out.println(threadName+" attact 30");
            System.out.println(threadName+" LifeValue="+lifeValue.getLifeValue());
        }        if(lifeValue.getFlag()<=0){
            System.out.println(threadName+" win");
        }
        return lifeValue.getFlag();
    }
    @Override
    public void run() {
        System.out.println("Running "+threadName);
        try{
            Thread.sleep(50);
            for(int i=5;i>0;i--){
                int flag=attack(threadName);
                if(flag<=0) break;                Thread.sleep(60);
            }
        }catch (InterruptedException e){
            System.out.println("Thread"+threadName+"interrupted.");
        }
        System.out.println("Thread"+threadName+"exiting.");
    }    public void start(){
        System.out.println("Starting "+threadName);
        if (thread==null){
            thread=new Thread(this,threadName);
            thread.start();
        }
    }
}

解决方案 »

  1.   


    看你的程序lifeValue应该是一个共享数据类,但是你每执行一个线程,lifeValue都是新建的,是不同的东西不会发生共享,所以你的锁不会起效果。锁只有加在共享的数据上才能保证共享数据同一时间内只被一个线程使用。
      

  2.   


    看你的程序lifeValue应该是一个共享数据类,但是你每执行一个线程,lifeValue都是新建的,是不同的东西不会发生共享,所以你的锁不会起效果。锁只有加在共享的数据上才能保证共享数据同一时间内只被一个线程使用。那样改的话是吧lifeValue在主程序中建立,然后再引用到线程里面吗,还有主程序建立要设置成静态的吗
      

  3.   


    看你的程序lifeValue应该是一个共享数据类,但是你每执行一个线程,lifeValue都是新建的,是不同的东西不会发生共享,所以你的锁不会起效果。锁只有加在共享的数据上才能保证共享数据同一时间内只被一个线程使用。那样改的话是吧lifeValue在主程序中建立,然后再引用到线程里面吗,还有主程序建立要设置成静态的吗一般是你需要调用的把lifeValue中的方法synchronized,把lifeValue类作为参数传给线程。你可以main里初始化变量,无需静态。
      

  4.   

    synchronized 应该锁的是 共享资源部分,防止多个线程同时访问