antony
antony

Reputation:

Create multiple Java Threads at once

Is there any possibility to create the threads as follows,

Thread odjhygThread= new Thread(objJob1, objJob2);

I think we couldn't, if we want to create what needs to be done? anyone knows the answer? Thanks in advance.

Upvotes: 0

Views: 638

Answers (4)

super_aardvark
super_aardvark

Reputation: 1855

I assume you're already aware of the Thread constructor that takes a Runnable as an argument. Are you trying to create a thread that calls run() on two different Runnable objects? This doesn't exist, but it would be easy to write:

public class RunTwoThings implements Runnable {

  private Runnalbe thing1;
  private Runnable thing2;

  public RunTwoThings(Runnable thing2, Runnable thing2) {
    this.thing1 = thing1;
    this.thing2 = thing2;
  }

  public void run() {
    thing1.run();
    thing2.run();
  }

}

You'd might want to do some exception handling to prevent problems in thing1 from preventing the execution of thing2. Then, just create a new thread like so:

Thread odjhygThread= new Thread(new RunTwoThings(objJob1, objJob2));

If that's not what you're trying to do (e.g. if you want them both to run simultaneously in their own threads), you probably want Steve M.'s answer above.

Upvotes: 0

Stu Thompson
Stu Thompson

Reputation: 38898

Yes (unless I am missing something here)

public class MyThread extends Thread {
    private final Object object1;
    private final Object object2;

    public MyThread(Object o1, Object o2) {
        //implicate call to super()
        object1 = o1;
        object2 = o2;
    }
    @Override
    public void run() {
        //ha ha
        //he he
        //ho ho
        //off to work we go
    }
}

Upvotes: 0

Steve McLeod
Steve McLeod

Reputation: 52468

A Thread runs one job. That's the way they are designed.

If you are trying to run two jobs, use two Threads.

If you want to hand over two jobs to be run in the background, read the JavaDocs for the Executors class, and the ThreadPoolExecutor class. It will take you a while to get your head around them, but unfortunately that's the nature of multi-threading in Java. Complicated.

Upvotes: 4

Tal Pressman
Tal Pressman

Reputation: 7317

I'm not sure this is what you're aiming for but.. Create a class that extends Thread, and give it a c'tor that takes 2 parameters.

Upvotes: 2

Related Questions