我如何计算依赖项.startService()的次数;方法调用?不同的服务正在调用此方法,我不想知道每个人都调用了多少次该方法,但单个服务。我应该得到这个输出:
My name is Service B and I'm depending on Service A
My name is Service C and I'm depending on Service A
My name is Service D and I'm depending on Service B
***Service Service C lets start!***
1
***Service Service D lets start!***
2
实际上这个数字应该意味着这两个依赖于多少服务。你对我该怎么做有什么想法吗?我已经尝试过,我只能获得调用该方法的全局数量,即 3。
这是我的代码:
ManagerService.java
import java.util.*;
import java.util.concurrent.CountDownLatch;
public class ManagerService
{
public static void main(String[] args) throws InterruptedException
{
//Creating Services
Service serviceA = new Service("Service A", "Thread A");
Service serviceB = new Service("Service B", "Thread B");
Service serviceC = new Service("Service C", "Thread C");
Service serviceD = new Service("Service D", "Thread D");
serviceB.dependesOn(serviceA);
serviceC.dependesOn(serviceA);
serviceD.dependesOn(serviceB);
System.out.println();
System.out.println("***Service " + serviceC.serviceName +" lets start!***");
serviceC.startService();
System.out.println();
System.out.println("***Service " + serviceD.serviceName +" lets start!***");
serviceD.startService();
}
}
and
Service.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
public class Service
{
public String serviceName;
public String threadName;
private boolean onOrOff = false;
public List <Service> dependentServicesOn = new ArrayList <Service>();
public CountDownLatch startSignal;
private Integer counter = 0;
public Service(String service_name, String thread_name)
{
this.serviceName = service_name;
this.threadName = thread_name;
}
public void dependesOn(Service s) throws InterruptedException
{
System.out.println("My name is " + serviceName +" and i'm depending on " + s.serviceName);
dependentServicesOn.add(s);
}
public Service startService() throws InterruptedException
{
for(Service dependency : dependentServicesOn) {
if(!dependency.isStarted()) {
dependency.startService();
}
}
startSignal = new CountDownLatch(1);
// new Thread(new CreateThread(this,startSignal)).start();
startSignal.countDown();
return null;
}
public boolean isStarted()
{
return onOrOff;
}
public void setStarted()
{
onOrOff = true;
}
}