在不同的线程中启动Java类

时间:2009-05-27 13:19:40

标签: java concurrency

我想知道如何从不同的线程调用一个类,并让所有调用都在它自己的线程中运行?

假设我有三个线程,并且每个线程都需要调用anotherClass.getBS(),但调用可能同时进行,并且没有理由在此时执行一个。死锁不是问题。

谢谢!

2 个答案:

答案 0 :(得分:7)

如果anotherClass.getBS()确实是线程安全的,你可以从你的三个线程中调用它。它将在你调用它的线程中运行。

这个实例的一个小例子。下面的代码产生了这个输出:

$ 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

以下是代码:

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

}

答案 1 :(得分:2)

如果您确定getBS()方法没有任何并发​​问题,只需正常调用该方法。

如果方法是static,只需执行:

AnotherClass.getBS();

否则

anotherClass obj的引用传递给每个线程:

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