我如何计算时间是多少依赖.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 dependentServicesOn = new ArrayList ();
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;
}
}