run()方法与其他类方法(java线程)之间的通信

时间:2013-06-17 14:35:53

标签: java multithreading list methods

我有任务要做,我有点卡住了。我必须提供4项服务(A,B,C,D)。每个服务都应该有自己的主题。它们应该按顺序启动并运行。如果服务A启动然后可以启动服务B,如果服务B启动,如果服务C启动然后可以启动服务D.我设法创建服务和他们的线程但我不知道我应该如何创建start()和priority()方法之间的通信在PriorityService类中。我想检查服务(线程)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);     

    }
}

2 个答案:

答案 0 :(得分:0)

如果要为每个服务创建不同的线程,则无法控制执行是线程(例如,通过设置其优先级等)。优先级只是操作系统的指标,但不能保证优先级较高的线程首先运行。

只有通过使用wait,notify,join等进行线程间通信才能实现此目的

但我想如果你的情况可以解决,可以为服务A,B,C和C的一个组合创建单独的线程。 d。

答案 1 :(得分:0)

你应该使用Latches。

您可以为每对线程使用2个锁存器,这应该可以完成您的工作。因此,一个Latch将出现在线程A和B中,这意味着直到它们都启动并运行它们才能继续。同样适用于C和D.

这个link有一个显示使用Latch的例子,请看一下。

相关问题