简体   繁体   中英

Communication between threads defined on two different instances of same class?

I have a class (say) Task.java which performs some task scheduling activity. This class contains two types of activities- 1) To schedule periodic tasks and 2) To schedule aperiodic tasks. Periodic task has higher priority over aperiodic.

public class Task implements Runnable{
  ArrayList<> list;
  public Task(ArrayList<> list){
    this.list = list;
  }
public void run(){
    handlePeriodicTask(){...}
    handleAPeriodicTask(){...}
  }
}

In main class, I've one global list of task which contains both periodic and aperiodic tasks. I am splitting this list into two sublists each containing different periodic tasks but may be repeating aperiodic tasks. And I'm supplying these sublists to two different threads created on two different instances of Task.java

public class Main{
  ArrayList<> globalList;

  //splitting globalList to get two sublists
  ArrayList<> subList1; 
  ArrayList<> subList2;
  public static void main(..){
     Task task1 = new Task(subList1);

     Task task2 = new Task(subList1);
     new Thread(task1).start();
     new Thread(task2).start();
  }
}

I want all periodic tasks in two sublists to be scheduled independently, however aperiodic, (since they are aperiodic in nature), need prior knowledge if it is already scheduled by another thread. If so, current thread should ignore them. I don't know how to achieve this communication via wait() notify() on two threads created on two different instances. I've seen several examples of wait() notify() that operates on single instance, but how to achieve this on two different instances. I'm not well versed in multithreading, so the question may stand silly/invalid, but I want proper guidance for that. Anybody please guide me. Thanks.

Never launch thread independently, if the solution you are trying to achieve will result into generation of too many threads. It is better to use Thread Pool Manager ( Executor Service - Link ). This will help you to achieve multiple things - Launching of threads in more controlled manner, configure number of threads (poolsize) based on environment, reliable mechanism to manage threads across all platforms. Your all periodic tasks can be given to ExecutorService to launch.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM