Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.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_Loops_Coding Style - Fatal编程技术网

创建线程,做点什么,杀死线程-所有内部循环[JAVA]

创建线程,做点什么,杀死线程-所有内部循环[JAVA],java,multithreading,loops,coding-style,Java,Multithreading,Loops,Coding Style,我是个新手。我需要实现这样的方法,它将创建2个线程,做一些事情,然后杀死它们——for循环中的所有东西 主要目的:我需要确保线程将以for循环中相同的“I”值并行工作。这就是为什么我没有在每个线程中声明for循环。(哪一个先完成我不在乎) 我的愿景 public void threadsJob() throws Exception{ for(int i = 1; i<1000 ; i++) { **final** int j =

我是个新手。我需要实现这样的方法,它将创建2个线程,做一些事情,然后杀死它们——for循环中的所有东西

主要目的:我需要确保线程将以for循环中相同的“I”值并行工作。这就是为什么我没有在每个线程中声明for循环。(哪一个先完成我不在乎)

我的愿景

          public void threadsJob() throws Exception{
          for(int i = 1; i<1000 ; i++) {
          **final** int j = i;
          Thread t1= new Thread(new Runnable() {
           public void run() {
                     foo(j);
                }     
           }
      );

          Thread t2= new Thread(new Runnable() {
           public void run() {
                     bar(j);
                }     
           }
      );

      t1.start();
      t2.start();

      t1.join();
      t2.join();
}}
public void threadsJob()引发异常{

对于(int i=1;i使用Executors.newFixedThreadPool(2)

执行两个执行您的工作的Runnable


然后关闭并等待ExecutorService终止。

根据foo和bar实际执行的操作,创建新线程所需的时间很可能比串行工作所需的时间长。请使用线程池。