synchronized 无效

S_mallBai S_mallBai 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
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();
}
}
}
...全文

相关推荐

评论 6
收藏 已收藏
分享
返回顶部
S_mallBai
Java SE 62,620 成员 307,251 内容