如何使用java中的输入值进行并行编程

时间:2017-02-22 07:16:50

标签: java multithreading multiprocessing

我在Java程序中实现推荐算法。

但是,我有严重的问题。数据集太大,计算速度太慢。所以,我需要用Java进行并行编程。

例如,

for (int i=0; i < 10000000 ; i++) { ~~~ }

我想将这些句子分开,例如

process 1: for (int i=0; i < 10000 ; i++)

process 2: for (int i=10001; i < 20000 ; i++)

process 3: for (int i=20001; i < 30000 ; i++)

...

我知道类似的方法in Python。如何在Java中进行并行编程?

1 个答案:

答案 0 :(得分:0)

希望这会对你有所帮助。

public class MyRunnable implements Runnable {
        private final long countUntil;

        MyRunnable(long countUntil) {
                this.countUntil = countUntil;
        }

        @Override
        public void run() {
                long sum = 0;
                for (long i = 1; i < countUntil; i++) {
                        sum += i;
                }
                System.out.println(sum);
        }
}



public class Main {

        public static void main(String[] args) {
                // We will store the threads so that we can check if they are done
                List<Thread> threads = new ArrayList<Thread>();
                // We will create 500 threads
                for (int i = 0; i < 500; i++) {
                        Runnable task = new MyRunnable(10000000L + i);
                        Thread worker = new Thread(task);
                        // We can set the name of the thread
                        worker.setName(String.valueOf(i));
                        // Start the thread, never call method run() direct
                        worker.start();
                        // Remember the thread for later usage
                        threads.add(worker);
                }
                int running = 0;
                do {
                        running = 0;
                        for (Thread thread : threads) {
                                if (thread.isAlive()) {
                                        running++;
                                }
                        }
                        System.out.println("We have " + running + " running threads. ");
                } while (running > 0);

        }
}

我是从here

获得的