synchronized 无效
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();
}
}
}