Java中的进程与线程 [英] Processes vs threads in Java

查看:69
本文介绍了Java中的进程与线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我已阅读的问题中,我们建议在进程上使用线程,因为线程速度更快.我决定使用程序的线程来编辑Wikipedia中某个类别的文章. 该程序获取要编辑的文章列表,然后将文章划分为10个线程.这样一来,我每分钟进行6-7次编辑,这与我没有使用线程的速度相同.当我启动程序的多个实例并为每个实例指定要处理的类别时,我看到每个进程每分钟可以进行6-7次编辑(我用5个进程进行了测试).

In the questions I have read we suggest to use threads over processes because threads are faster. I decided go with threads for my program that edit articles in a category in Wikipedia. The program get the list of articles to edit and then divide the articles between 10 threads. By this I do 6-7 edits per minute and it's the same speed as if I haven't used threads. When I launch multiple instance of my program and give for each instance a category to process I see that each process can do 6-7 edits per minute (I tested that with 5 processes).

为什么我的流程要快得多?以及为什么线程没有进行任何更改?

Why processes are much faster in my case? and why the threads haven't changed anything?

代码(不完整,只是一个想法):

The code (Not the complete just to have an idea) :

 public static wiki = new Wiki();

 public process(){
      String[] articles = wiki.getArticles(category);

      for(int i=0; i< 10; i++){
            String[] part = getPart(articles, i, 10); 
            MyThread t = new MyThread(part);
            list.add(t);
      }
      ExecutorService.invokeAll(list); //I'm not sure about the syntax of the function
 }

public class MyThread extends Thread {
     public String[] articles ;

     public MyThread(String[] articles) {
         this.articles = articles;
     }

     public void run() {
         //some logic
         wiki.edit(...)
     }
} 

推荐答案

每个进程都有许多线程来完成其工作.如果您有一个带有N个线程的进程或一个带有1个线程的N进程,那么除了没有什么区别.

Each process has a number of threads to do it's work. If you have one process with N threads or N process with 1 thread, it makes little difference except.

  • 线程的重量更轻,开销也稍少.他们造成的差异以毫秒为单位,因此您不太可能在这里获得.
  • 使用更多的进程,间接允许您的程序使用更多的内存(由于每个进程的堆大小有限,您可以更改).如果您要拥有N个进程,则公平的比较是将每个进程的内存限制为1/N的内存量.
  • 更有可能发生的事情是您正在限制诸如锁之类的共享资源.这意味着您的附加线程几乎没有价值,因为您的程序无法有效地使用它们.通过使用多个进程,您可以断开线程之间的连接.

我看到每个进程每分钟可以进行6-7次编辑

I see that each process can do 6-7 edits per minute

每次编辑耗时10秒听起来很长.也许有必要使用CPU事件探查器优化代码以提高性能.

Each edit taking 10 seconds sounds pretty long. Perhaps there is worth optimising your code with a CPU profiler to improve your performance.

这篇关于Java中的进程与线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆