views:

179

answers:

2

Hi all!

I'm wondering how i can call a class from different threads, and have all the calls run in it's own thread?

Lets say I have three threads, and each of them need to call anotherClass.getBS(), but the calls might come at the same time, and there's no reason to perform them one at the time. Deadlocks are not a problem.

Thanks!

+7  A: 

If anotherClass.getBS() really is thread-safe, you can just call it from each of your three threads. It'll run within the thread that you called it from.

A small example of this in action. The code below produces this output:

$ javac Bar.java
$ java Bar
Thread ID 9 running
Thread ID 10 running
Thread ID 8 running
Doing something on thread 9
Doing something on thread 10
Doing something on thread 8
Thread ID 9 running
Doing something on thread 9
Thread ID 8 running
Doing something on thread 8
Thread ID 10 running
Doing something on thread 10

Here's the code:

public class Bar
{

  static private final class MyOtherClass
  {
    public void doSomething()
    {
      System.out.println("Doing something on thread "+Thread.currentThread().getId());
    }
  }

  static private MyOtherClass myOtherClass=new MyOtherClass();

  static private final class MyThreadClass implements Runnable
  {
    public void run()
    {
      while (true)
      {
        try
        {
          Thread.sleep(1000);
        }
        catch (InterruptedException ie)
        {
          System.err.println("Interrupted");
          return;
        }
        System.out.println("Thread ID "+Thread.currentThread().getId()+" running");
        myOtherClass.doSomething();
      }
    }
  }

  static public void main(String[] args)
  {
    Thread t1=new Thread(new MyThreadClass());
    Thread t2=new Thread(new MyThreadClass());
    Thread t3=new Thread(new MyThreadClass());
    t1.start();
    t2.start();
    t3.start();
  }

}
Jon Bright
+1  A: 

If you are sure that the getBS() method doesn't have any concurrency issues just call the method normally.

If the method is static just do:

AnotherClass.getBS();

else

Pass a reference of anotherClass obj to each thread:

 class MyThread extends Thread {
     private AnotherClass anotherClass;

     MyThread(AnotherClass anotherClass) {
         this.anotherClass= anotherClass;
     }

     public void run() {
         anotherClass.getBS();
     }
 }


 MyThread p = new MyThread(anotherClass);
 p.start();
bruno conde
The questioner appears to have enough trouble working out what a thread is without extending Thread.
Tom Hawtin - tackline
Why the down vote???
bruno conde
No idea who downvoted you and why, but your answer's also good afaics.
Jon Bright