views:

185

answers:

3

Hi,

Thread class has run method to implement the business logic that could be executed in parallel.But I want implement different business logics in a single run method and to run simultaneously.How to get this feature.

thanks

A: 

Make this run method spawn new thread with one logic and another thread with the second logic.

Itay
But both will call the same run() method ...right?
JavaUser
+1  A: 

That's right. You implement (or override) the run-method of a Thread to do stuff in parallell, however, there is an important difference when calling run vs calling start.

There is nothing special with the run method. Calling run will behave just like any call to a regular method, and the control will not return to the caller until the run method has finished. The magic happens in start. When calling start the control is returned to the calling side immediately, and a new thread is spawned that has the run method as entry point.

So, for example, if you want to execute two tasks simultaneously in different threads, you do something like:

Thread t = new Thread() {
    public void run() {
        doTask1();
    }
};

// Spawn a new thread that doTask1. (don't call run here!)
t.start();
// Control returns immediately while thread t is busy with doTask1.

doTask2();

An example run:

    Thread t = new Thread() { 
        public void run() {
            try {
                Thread.sleep(1000);
                System.out.println("Slept for 1 second.");
            } catch (InterruptedException e) {
            }
        }
    };

    t.run();
    System.out.println("Returned from run.");

    t.start();
    System.out.println("Returned from start.");

Yields output

                       (one second pause)
Slept for 1 second.
Returned from run.
Returned from start.
                       (one second pause)
Slept for 1 second.
aioobe
+1  A: 

I think that the best course of action would be to have two separate threads.

You can (and probably should) write a new class that implements Runnable and inside it place your logic. If there are common activities between the two business logics that you have to implement, you can use this class as a base class for the two "Runnables". Each Runnable should be spawned in a separate thread.

You can find very good reasoning for Thread vs. Runnable on this post: http://stackoverflow.com/questions/541487/java-implements-runnable-vs-extends-thread

RonK