2011-07-21 121 views
3

我想弄清楚如何在java中多线程。现在,我的程序运行正常,没有并发性,但我想实现多线程来帮助加快速度。多线程java

该程序运行一个单独的子类的几个对象,每个这些对象的50%的时间评估花费在一个只使用一个内核而不是8个可用内核的进程中。这些对象直到彼此完全独立,但在程序中用作输入。

我想通过让子类实现Runnable来让它多线程化,然后让我的程序为每个这样的对象使用一个线程。这是否是正确的方法?

但是,java中的线程如何处理?我需要在每次运行后处理线程吗?如何加入工作?

谢谢

+2

如果你写了一个重要的应用程序,你应该看看理论:http://download.oracle.com/javase/tutorial/essential/concurrency/。否则,你会很难学会它:-) – home

回答

5

你几乎走上正轨。您将创建一个Thread对象

Runnable r = new MyClassImplementingRunnable(); 
Thread t = new Thread(p); 
t.start(); 
t.join(); // wait for thread to die 

线程对象是收集像任何其他对象的,垃圾,run方法完成时线程本身死亡。关键是你的Runnable的运行方法确实必须保证返回,你的设计不能依赖于能够从外部杀死线程。

如果您要有很多线程,您需要等待它们全部完成,因此您可以保留已开始线程的集合,然后使用t.join(smallNumberOfMillis)来查看哪些他们已经完成了。这有点低效,所以还有其他技术可以让线程相互通信,我建议读取this article

@denis还提到Executor和相关类提供了一个更好的线程上面的抽象。如果您对学习背景有兴趣,那么手动管理线程很有趣。如果你只是想完成这项工作,请按照Denis的建议。

+0

不会主动管理线程:) –

+0

好的,这是他首先学习底层细节还是使用更好的抽象。 – djna

+0

如何在子类中设置run方法?现在我得到一个抛出的空指针异常错误 – randomafk

7

不要手动管理线程,在Java

+0

我会稍后再研究它,但我想先了解一下hte基础知识 – randomafk

+1

@randomafk:这些*都是基础知识。 –

3

看看executors and thread pools看看http://download.oracle.com/javase/1,5.0/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html

构造函数你想要的线程数。在这种情况下,核心数量相同。

ScheduledThreadPoolExecutor s = new ScheduledThreadPoolExecutor(8); 
List<Future> futures = new ArrayList<Future>(); 
foreach(...something...) 
    futures.add(s.submit(new MyCallable())); 
foreach(Future f : futures) 
    f.get(); // Result of computation 
System.out.println("Done"); 
+0

MyCallable类是否需要像Runnable一样具有特殊的运行功能? – randomafk

+0

是可调用类似于Runnable,除了定义为接口可调用 {V call(); }所以他们可以返回你喜欢的类型的对象。 http://download.oracle.com/javase/1,5.0/docs/api/java/util/concurrent/Callable.html –

0

这是启动多线程的好方法。

public class ThreadExample { 
    public static void main(String[] args) { 
     //Main thread 
     System.out.println("Main thread"); 
     new Thread(new Runnable() { 
      @Override 
      public void run() { 
       //This thread is independent of the main thread 
       System.out.println("Inner Thread"); 
      } 
     }).start(); 
    } 
}