Coder
Coder

Reputation: 97

Java Multithreading : Job scheduling

I have two jobs J3 & J5 where,

  1. J3 starts only after completion of jobs J1 & J2
  2. J5 starts only after completion of job J4
  3. These two jobs(J3 & J5) need to be executed in two different threads.
  4. J3 & J5 threads need to run simultaneously

How can it be programmed in Java?

Upvotes: 0

Views: 213

Answers (3)

WhiteFang34
WhiteFang34

Reputation: 72039

Are J1, J2 and J4 also threads? You could pass them into your other jobs and use Thread.join() to wait for them to complete. For example the first 3 threads:

Thread j1 = new Job1Thread();
Thread j2 = new Job2Thread();
Thread j3 = new Job3Thread(j1, j2);
// start them up, etc.

public class Job3Thread extends Thread {
    private final Thread j1;
    private final Thread j2;

    public Job3Thread(Thread j1, Thread j2) {
        this.j1 = j1;
        this.j2 = j2;
    }

    public void run() {
        try {
            j1.join();
            j2.join();
            // now start processing
        } catch (InterruptedException ie) {
        }
    }
}

Upvotes: 3

Peter Lawrey
Peter Lawrey

Reputation: 533442

You didn't say jobs J1 and J2 have to be concurrent so the simplest thing to do is

// thread one
J1();
J2();
J5();

// thread two
J3();
J4();

The simplest way to have one task follow another is to have method calls in the same thread one after they other. ;)

Upvotes: 0

gshauger
gshauger

Reputation: 745

You could always create a master thread that checks to see what the status is of the various threads are. Once it sees that J1 & J2 are done it then fires off J3. The same logic could be applied for J4 and J5.

J3 and J5 could run in parallel as a result of this.

The status can be determined by placing a boolean value in your threads such as "running".

Upvotes: 0

Related Questions