有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java中的多线程线程作业

我想在Java中同时产生200个线程。我现在正在做的是运行一个循环,创建200个线程并启动它们。在这200个线程完成后,我想再生成200组线程,以此类推

这里的要点是,我生成的前200个线程需要在生成下一组之前完成。我尝试了下面的代码,但它不起作用

for(int i=0;i<200;i++){
    Thread myThread = new Thread(runnableInstance);
    myThread.start();
}
for(int i=0;i<200;i++){
    Thread myThread = new Thread(runnableInstance);
    myThread.start();
}

注意:我有意将for循环放了两次,但我想要的效果不会发生,因为第二个for循环是在第一组线程结束执行之前执行的

请告知


共 (6) 个答案

  1. # 1 楼答案

    您应该保留已创建线程的列表。然后,一旦启动了所有列表,就可以在列表上循环并对每个列表执行join。当连接循环完成时,所有线程都将运行到完成

    List<Thread> threads = new List<Thread>();
    for(int i=0;i<200;i++){
        Thread myThread = new Thread(runnableInstance);
        myThread.start();
        threads.add(myThread);
    }
    //All threads are running
    for(Thread t : threads) {
        t.join();
    }
    //All threads are done
    
  2. # 2 楼答案

    您需要使用join()等待线程完成:

    // run first set of threads
    List<Thread> threads = threadsList; // save reference to all threads
    for(Thread t : threads){
        t.join();
    }
    // all threads finished
    
    // run other set of threads
    
  3. # 3 楼答案

    如果您使用的是Java1.5,那么就使用并发包,如果您使用的是Java1.4.2,那么这个包仍然可以作为一个后端口使用,我非常确定

    尽管如此,我最近也有类似的任务要做;通过使用ExecutorService来了解任务是否完成,可以非常轻松地实现这一点。非常干净的模式-可能不完全是您想要实现的,但在现实生活中它工作得非常好:-)

    一些代码:

    BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>();
    taskExecutor = new ThreadPoolExecutor(200, 200, 30, TimeUnit.SECONDS, workQueue);
    
    futureList.add(taskExecutor.submit(new MyCallable()));
    
    for (Future<Object> future : futureList) {
        future.get(); // wait for the task to complete
    }
    
    //... instantiate your second group of executors
    
  4. # 4 楼答案

    感觉像是在做家务,但是

    spawnAndWait() {
     Thread T[] = new Thread[n];
     for(int i=0;i<n;i++){
         T[i] = new Thread(runnableInstance);
         T[i].start();
     }
     for (Thread t : T) {
      t.join();
     }
    }
    
  5. # 5 楼答案

    另一个解决方案是使用闩锁

    final CountDownLatch latch = new CountDownLatch(200);
    
      for(int i=0; i<10; i++)
    {
    
     Thread thread = new Thread()
    {
        public void run()
    {
         try{
             //do your work  
    
         }finally{
          latch.countDown();
         }
        }
       };
    
         }  
                //will block here util your threads all finished
      latch.await();
    
  6. # 6 楼答案

    某种伪代码,您可以调用acnt实例;-)

    while( moreThreads ) {
        List<Callable<Integer>> threads = new ArrayList<Callable<Integer>>();
        for( int i = 0; i < 200; ++i ) {
            threads.add(new Callable<Integer>() );
        }
    
        FixedThreadPool pool = Executers.newFixedThreadPool(200);
        pool.invokeAll(threads);
        pool.shutdown();
    }