【发布时间】:2013-06-13 13:29:07
【问题描述】:
我有任务要做,我有点卡住了。我必须提供 4 项服务(A、B、C、D)。每个服务都应该有自己的线程。它们应该按顺序启动并运行。如果服务 A 启动,则可以启动服务 B,如果服务 B 启动,如果服务 C 启动,则可以启动服务 D。我设法创建服务及其线程,但我不知道应该如何在 start() 和 priority() 方法之间创建通信在 PriorityService 类中。我想检查服务(线程)A是否还活着,如果它是我想从列表中移到第二个服务等等。那可能吗?您还有其他想法如何编写服务依赖项吗? 任何建议都是有用的。肿瘤坏死因子。
这是我的代码:
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);
}
}
【问题讨论】:
-
在
CreateThread的构造函数中通读-i=numb好像错了,不应该反过来吗? -
在当前线程上调用
join不会做任何事情。 -
因为我试图将 int i 从 while 循环发送到 CreateThread 类,然后如果该线程还活着,那么我 ++ 女巫在 run() 方法中变得麻木并将其发送到 while在 priority() 方法中循环。我不知道这是否是个好主意,因为我是编程新手。
-
@seling with join 方法我正在尝试运行所有线程而不会弯腰。正如我所说,我不知道这是否是个好主意:S 我很困惑......
-
调用
Thread.currentThread().join();将挂起,直到线程被中断,这可能不是你想要的。
标签: java multithreading list methods