我有任务要做,我有点卡住了。我需要提供4种服务(A B C D)每个服务都应该有自己的线程。它们应该按顺序启动并运行。如果服务A启动,那么可以启动服务B,如果服务B启动,如果服务C启动,那么可以启动服务d。我设法创建服务和它们的线程,但我不知道我应该如何在PriorityService类中创建start()和priority()方法之间的通信。我想检查服务(线程)A是否活着,如果是,我想从列表中移动到第二个服务,等等。这可能吗?你对如何编写服务依赖有什么其他的想法吗?任何建议都是有用的。Tnx。
下面是我的代码:import java.util.*;
class CreateThread extends Thread{
private String thread_name;
public int numb;
public CreateThread(String thread_name, int i){
this.thread_name=thread_name;
System.out.println("Thread " + thread_name + " has started.");
i=numb;
}
public void run(){
try{
Thread t = Thread.currentThread();
System.out.println(thread_name + " status = " + t.getState());
System.out.println(thread_name + " status = " + t.isAlive());
t.join();
}catch(Exception e){
System.out.println(e);
}
}
}
class PriorityService extends ArrayList<Service> {
public void priority()
{
int i=0;
while(i<size()){
System.out.println("evo me"+ get(i).service_name);
if(get(i).service_name=="Service A")
get(i).StartService(get(i).service_name, get(i).thread_name, i);
i++;
}
}
}
public class Service {
public String service_name;
public String thread_name;
public Service(String service_name, String thread_name){
this.service_name=service_name;
this.thread_name=thread_name;
}
public void StartService(String service_name, String thread_name, int i) {
System.out.println("Service " + service_name + " has started.");
Thread t=new Thread(new CreateThread(thread_name, i));
t.start();
}
public void StopService() {}
public static void main (String[] args){
PriorityService p_s=new PriorityService();
Service service_A = new Service("Service A", "Thread A");
Service service_B = new Service("Service B", "Thread B");
Service service_C = new Service("Service C", "Thread C");
Service service_D = new Service("Service D", "Thread D");
p_s.add(service_A);
p_s.add(service_B);
p_s.add(service_C);
p_s.add(service_D);
p_s.priority();
for(Service s: p_s)
System.out.println(s.service_name);
}
}
如果你为每个服务创建不同的线程,那么你就不能控制线程的执行(例如通过设置其优先级等)。优先级只是操作系统的一个指标,但不能保证优先级高的线程优先运行。
唯一的方法是通过线程间通信使用wait, notify, join等。
但我认为在你的情况下,解决方案可能是,为服务A, B, C的一个组合创建单独的线程;d .
你应该使用latch
你可以为每对线程使用2个latch,这应该可以完成你的工作。因此,线程A和B将有一个Latch,这意味着直到它们都启动并运行它们才能继续。C和d也一样。
这个链接有一个使用Latch的例子,请看