Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Java中设置以下线程?_Java_Multithreading - Fatal编程技术网

如何在Java中设置以下线程?

如何在Java中设置以下线程?,java,multithreading,Java,Multithreading,我有以下形式的线程: 每个线程的每次执行都应该在类中运行一个函数。该函数可以完全安全地自行运行。该函数返回一个值,比如int 执行完所有线程后,需要累积函数值 所以,它(在伪代码中)是这样的: a = 0 for each i between 1 to N spawn a thread independently and call the command v = f(i) when thread finishes, do safely: a = a + v e

我有以下形式的线程:

  • 每个线程的每次执行都应该在类中运行一个函数。该函数可以完全安全地自行运行。该函数返回一个值,比如int

  • 执行完所有线程后,需要累积函数值

  • 所以,它(在伪代码中)是这样的:

      a = 0
      for each i between 1 to N
          spawn a thread independently and call the command v = f(i)
          when thread finishes, do safely: a = a + v
      end
    
    我不知道在那种情况下如何使用Java

    问题不是创建线程,我知道可以使用

    new Thread() { 
       public void run() { 
         ... 
       } 
    } 
    
    问题在于积累所有答案


    谢谢你提供的任何信息。

    我可能会这样做:

     public class Main {
         int a = 0;
         int[] values;
         int[] results;
    
         public Main() {
             // Init values array
    
             results = new int[N];
         }
    
         public int doStuff() {
             LinkedList<Thread> threads = new LinkedList<Thread>();
    
             for (final int i : values) {
                 Thread t = new Thread() {
                     public void run() {
                         accumulate(foo(i));
                     }
                 };
    
                 threads.add(t);
                 t.start();
              }
    
              for (Thread t : threads) {
                  try {
                      t.join();
                  } catch (InterruptedException e) {
                      // Act accordingly, maybe ignore?
                  }
              }
    
              return a;
         }
    
         synchronized void accumulate(int v) {
              // Synchronized because a += v is actually
              //    tmp = a + v;
              //    a = tmp;
              // which can cause a race condition AFAIK
              a += v;
         }
     }
    
    公共类主{
    int a=0;
    int[]值;
    int[]结果;
    公用干管(){
    //初始化值数组
    结果=新的整数[N];
    }
    公共int DOSTAFF(){
    LinkedList线程=新建LinkedList();
    用于(最终int i:值){
    线程t=新线程(){
    公开募捐{
    累积(foo(i));
    }
    };
    添加(t);
    t、 start();
    }
    用于(螺纹t:螺纹){
    试一试{
    t、 join();
    }捕捉(中断异常e){
    //相应地行动,也许忽略?
    }
    }
    返回a;
    }
    同步无效累积(int v){
    //已同步,因为a+=v实际上是
    //tmp=a+v;
    //a=tmp;
    //这可能会导致比赛状态
    a+=v;
    }
    }
    
    使用
    ExecutorCompletionService
    Executor
    Callable

    从调用
    int
    函数的
    Callable
    开始:

    public class MyCallable implements Callable<Integer> {
        private final int i;
    
        public MyCallable(int i) {
            this.i = i;
        }
    
        public Integer call() {
            return Integer.valueOf(myFunction(i));
        }
    }
    
    10
    是一次执行的最大线程数

    然后将其包装在一个
    ExecutorCompletionService
    中并提交作业:

    CompletionService<Integer> compService = new ExecutionCompletionService<Integer>(executor);
    
    // Make sure to track the number of jobs you submit
    int jobCount;
    for (int i = 0; i < n; i++) {
        compService.submit(new MyCallable(i));
        jobCount++;
    }
    
    // Get the results
    int a = 0;
    for (int i = 0; i < jobCount; i++) {
        a += compService.take().get().intValue();
    }
    
    这将在任务完成时更新UI。使用
    Thread.join
    不一定能做到这一点,因为您将按照调用连接的顺序获得结果,而不是按照线程完成的顺序


    通过使用executor,这还允许您限制在给定时间运行的同时作业的数量,这样您就不会意外地对系统进行线程轰炸。

    对Java没有太多经验,但我建议从Java中查看ForkJoin的内容。。7.我想是的。试试这个:你的想法很好。记住要面向接口编写代码,请使用
    List threads=new classthattheimplementsList()
    而不是声明
    LinkedList
    。当然,如果您不需要更新代码中除
    a
    之外的任何内容,则使用
    线程。加入
    即可:)
    
    CompletionService<Integer> compService = new ExecutionCompletionService<Integer>(executor);
    
    // Make sure to track the number of jobs you submit
    int jobCount;
    for (int i = 0; i < n; i++) {
        compService.submit(new MyCallable(i));
        jobCount++;
    }
    
    // Get the results
    int a = 0;
    for (int i = 0; i < jobCount; i++) {
        a += compService.take().get().intValue();
    }
    
    for (int i = 0; i < jobCount; i++) {
        a += compService.take().get().intValue();
        updateUi(a);
    }