如何計算可能的次數是多少次dependency.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;
}
}
沒有必要在標題中添加主標籤。 –
你爲什麼說「D」應該是2?是因爲D依賴於B,然後B依賴於A?你想以這種方式遍歷依賴關係列表嗎? –
@DariusX。是的,我試圖得到那樣的數字。你認爲這不是好的方法嗎? – njamanjam