Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting a Java class in different threads

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!

like image 891
drRoflol Avatar asked Sep 02 '26 06:09

drRoflol


2 Answers

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();
  }

}
like image 177
Jon Bright Avatar answered Sep 04 '26 22:09

Jon Bright


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();
like image 27
bruno conde Avatar answered Sep 04 '26 22:09

bruno conde



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!