【问题标题】:How to make parallel programming with input values in java如何在java中使用输入值进行并行编程
【发布时间】:2017-07-12 02:48:54
【问题描述】:

我在 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如何进行并行编程?

【问题讨论】:

  • 你是说线程?当人们并行编码时,不是并行编程吗?就像结对编程......但并行!只需使用 Java 线程
  • 你可以考虑使用 Java 8 的并行流......

标签: java multithreading multiprocessing


【解决方案1】:

希望这会对你有所帮助。

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得到它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-15
    • 1970-01-01
    相关资源
    最近更新 更多