如何在Java中进行多线程并行化任务?

时间:2015-05-03 18:38:32

标签: java multithreading

我在类中有一个方法可以进行一些计算:

class ParticleSystem:
    int size;
    double weight;
    ArrayList<Particle> P;
    public void updatePosition(){
          work on LIST P;  // <---- can be done in parallel
    }
    public void updateVelocity(){
          work on LIST P;  // <---- can be done in parallel
    }

    public void updateFrame(){  // <---- Invoked for each frame
          updatePosition();
          updateVelocity();
    }

    public static void main(){
          while(true){
               updateFrame(); // <----- render to screen
          }
    }
}

因此,每个updatePosition()和updateVelocity()调用都可以在粒子之间并行化。所以我想开发一种多线程这两项任务的有效方法。

因此,经过对java多线程的一些研究,我发现我可以实现一个实现Runnable的线程类。通过在每次迭代中创建新线程并将这两个方法放入run()方法,我可以执行这两个任务。 但是,这种方式创建线程有很多开销(我有4个核心8线程处理器,所以我每次迭代创建8个线程) 我读到了Executors和ThreadPool对象。我不太清楚如何使用它们。如果使用它们是个好主意,请给我一些示例用法帮助我!很多人赞赏!

编辑1:

class Particle:
    double x_position, y_position, z_position;
    double x_newPosition, y_newPosition, z_newPosition;

前面提到的2个任务不需要同步,这意味着他们需要x_positions并更新x_newPositions。但是,在每个任务之后,所有线程都应该加入,然后继续执行下一个任务。

1 个答案:

答案 0 :(得分:0)

您可以将Executor Service与缓存线程池执行程序一起使用。 如果有的话,您必须处理线程问题。 示例代码如下。

# Adapted from here: http://effbot.org/zone/tkinter-autoscrollbar.htm

from Tkinter import Scrollbar

class AutoScrollbar(Scrollbar):
    '''
    A scrollbar that hides itself if it's not needed. 
    Only works if you use the grid geometry manager.
    '''
    def set(self, lo, hi):
        if float(lo) <= 0.0 and float(hi) >= 1.0:
            self.grid_remove()
        else:
            self.grid()
        Scrollbar.set(self, lo, hi)

    def pack(self, *args, **kwargs):
        raise TclError('Cannot use pack with this widget.')

    def place(self, *args, **kwargs):
        raise TclError('Cannot use pack with this widget.')
相关问题