Java多线程类方法?

Java多线程类方法?,java,multithreading,methods,parallel-processing,Java,Multithreading,Methods,Parallel Processing,我不熟悉Java中的多线程,我想知道是否可以并行执行类中的方法。因此,与此相反: public void main() { this.myMethod(); this.myMethod(); } 。。。如果类中的每个方法都是在前一次调用完成后激发的,那么它们将并行执行。我知道下面的例子是可以做到的,但这涉及到创建新类,我希望避免这样做: public class HelloRunnable implements Runnable { public void run() {

我不熟悉Java中的多线程,我想知道是否可以并行执行类中的方法。因此,与此相反:

public void main() {
  this.myMethod();
  this.myMethod();
}
。。。如果类中的每个方法都是在前一次调用完成后激发的,那么它们将并行执行。我知道下面的例子是可以做到的,但这涉及到创建新类,我希望避免这样做:

public class HelloRunnable implements Runnable {
  public void run() {
    System.out.println("Hello from a thread!");
  }

  public static void main(String args[]) {
    (new Thread(new HelloRunnable())).start();
  }
}
我只是想说清楚,我看到了,但这对我毫无帮助

解决这个问题的关键是使用
公共静态
方法吗?无论哪种方式,是否有人可以举例说明如何使用他们的解决方案实现这一点


谢谢你抽出时间

抱歉,根据您的限制,无法执行此操作。如果不创建
thread
对象和包含
run()
方法的对象,就不能在Java线程中运行任何东西:要么是实现
Runnable
的单独类,要么是扩展
thread
的类。你所指的问题正好说明了该做什么;没有“更好”的答案,也没有其他答案。

我可能会这样做。CountDownLatch和Executors类是Java5中方便的实用程序,可以简化这类工作。在此特定示例中,CountDownLatch将阻塞main(),直到两个并行执行完成

(为了回答你的问题:这比你想象的还要糟糕!你必须编写更多的代码!)


啊。。。好吧我想我最终会使用更多的代码。:)谢谢你,欧内斯特!
ExecutorService EXECUTOR_SERVICE = Executors.newCachedThreadPool();

public void main() {
  final CountDownLatch cdl = new CountDownLatch(2); // 2 countdowns!
  Runnable r = new Runnable() { public void run() {
    myMethod();
    cdl.countDown();
  } };

  EXECUTOR_SERVICE.execute(r);
  EXECUTOR_SERVICE.execute(r);

  try {
    cdl.await();
  } catch (InterruptedException ie) {
    Thread.currentThread().interrupt();
  }
}