并行运行 100 个线程,如果之前的线程已完成,则运行缺失的线程

发布于 2024-10-29 02:21:12 字数 760 浏览 1 评论 0原文

例如,我需要始终运行 100 个线程来执行某些操作。 我有一个名为 ThreadsWorker 的类,它查找线程计数并在前面的一些线程完成时运行丢失的线程。 因此,这是描述情况的表格:

1 second: 100 threads
2 second: 92 threads (ThreadsWorker generates new 8 threads)
3 second: 100 theads
4 second: 72 threads (ThreadsWorker generates 28 threads)

等等。 我的线程是匿名调用(只是 new Thread(new Runnable(...)).start()),因为我不知道如何正确地将它们保存到 Threads[] 数组,因为虽然 ThreadsWorker 会保存 threads[i] = new Threads(),但某些线程可能会完成,然后会与数组索引发生一些冲突。

由于匿名调用,我现在使用 threadsCount 变量,并在线程主体开始处递增它,并在线程主体结束处递减(使用 synchronized)。好的,它工作正常,我的唯一方法是使用 while() 循环,在进度完成时检查 threadsCount == 0 是否。

我认为这是 C 风格,而不是 Java 风格:)那么,你能帮我用 Java 风格来做吗?

For example I need to always run 100 threads to do some action.
I have class which called ThreadsWorker which looks for threads count and runs missing threads if some previous are finished.
So, this is the table which describes situation:

1 second: 100 threads
2 second: 92 threads (ThreadsWorker generates new 8 threads)
3 second: 100 theads
4 second: 72 threads (ThreadsWorker generates 28 threads)

And so on.
My threads are anonymous calls (just new Thread(new Runnable(...)).start()) because I don't know how to correctly save them to Threads[] array because, while ThreadsWorker will save threads[i] = new Threads(), some threads may be finished and then there will be some collision with array indexes.

Because of anonymous calls I use threadsCount variable now and increment it in threads body beginning and decrements in threads body end (using synchronized). Okay, it works correctly and my single way is to use while() loop which checks if threadsCount == 0 when the progress is complete.

I think that this is C-style but not Java-way :) So, can you help me to do it in Java-way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

真心难拥有 2024-11-05 02:21:12

如果您的目标只是让 100 个线程主动处理,我建议查看 Java 线程池 (以及更一般的执行器)。

我不清楚您是要让所有 100 个线程继续运行还是等待它们全部完成。您的问题同时引用了两者(ThreadsWorker 生成 28 个新线程,threadsCount==0),它们似乎是矛盾的。

If your goal is simply to have 100 threads actively processing, I suggest looking at Java thread pools (and Executors more generally).

I'm unclear as to whether you want to keep all 100 threads going or wait for them all to finish. Your question references both (ThreadsWorker spawning 28 new threads, threadsCount==0) and they seem contradictory.

左耳近心 2024-11-05 02:21:12

将所有线程放入数组或集合中。

然后循环遍历集合,对每个集合调用 Thread.join() 。当这个循环完成时,所有线程都完成了。

ArrayList threads = new ArrayList();
for (int i = 0; i < 5; i++) {
  Thread t = new AweseomeThread();
  t.start();
  threads.add(t);
}

for (Thread t : threads) {
  t.join();
}

您还需要一些异常处理(例如 InterruptedException)。但是,我会将其作为读者的练习......:)

Put all the threads into an array or collection.

Then loop through the collection calling Thread.join() on each. When this loop completes, all threads are done.

ArrayList threads = new ArrayList();
for (int i = 0; i < 5; i++) {
  Thread t = new AweseomeThread();
  t.start();
  threads.add(t);
}

for (Thread t : threads) {
  t.join();
}

You'll need some exception handling too (such as InterruptedException). But, I'll leave that as an exercise for the reader... :)

寄人书 2024-11-05 02:21:12

http://download.oracle.com/javase /6/docs/api/java/util/concurrent/CountDownLatch.html

你可以尝试类CountDownLatch jdk api

private CountDownLatch latch;
private static class SimpleThread extends Thread {
 public void run() {
  latch.countDown();
 }
}
public static void main(String[] args) {
 int threadcount = 10;
 latch = new CountDownLatch(threadcount);
 for (int i = 0; i < 10; i++) {
  Thread t = new SimpleThread();
  t.start();
 }
 // waiting threads all finished
 latch.await();
}

从属性latch中获取线程计数主班

http://download.oracle.com/javase/6/docs/api/java/util/concurrent/CountDownLatch.html

You can try class CountDownLatch jdk api

private CountDownLatch latch;
private static class SimpleThread extends Thread {
 public void run() {
  latch.countDown();
 }
}
public static void main(String[] args) {
 int threadcount = 10;
 latch = new CountDownLatch(threadcount);
 for (int i = 0; i < 10; i++) {
  Thread t = new SimpleThread();
  t.start();
 }
 // waiting threads all finished
 latch.await();
}

Fetch the thread count from attibute latch of the Main class

是你 2024-11-05 02:21:12

我相信您正在尝试让 ThreadWorker 为所有已完成的线程提交新线程。

我会使用一个 BlockingQueue,线程(您的可运行对象)在完成时添加到其中。 ThreadWorker 将等待一个线程完成,然后启动一个新线程。

public class YourRunnable implements Runnable {
  private final BlockingQueue<YourRunnable> queue;
  public YourRunnable(BlockingQueue<YourRunnable> queue){
    this.queue = queue;
  }
  public void run{
      // Your Code...
      // Finished Processing
      queue.add(this);
  }
}
public class ThreadWorkder implements Runnable { 
  private final BlockingQueue<YourRunnable> queue;
  ThreadWorker(BlockingQueue<YourRunnable> queue){
    this.queue = queue;
  }
  public void run{
    while(queue.take()){
       (new Thread(new YourRunnable(queue))).start();
    }
  }
  // general main method
  public static void main(String [] args){
    BlockingQueue<YourRunnable> queue = new LinkedBlockingQueue<YourRunnable>();
    ThreadWorker worker = new ThreadWorker(queue);
    Thread(worker).start();
    for (int i = 0; i < 100; i++){
      (new Thread(new YourRunnable(queue))).start();
    }
  }
}

I believe you are trying to have ThreadWorker submit new threads for all thread that have been completed.

I'd use a BlockingQueue that threads (Your Runnable(s)) add to when complete. ThreadWorker will wait until a thread completes and then will start a new thread.

public class YourRunnable implements Runnable {
  private final BlockingQueue<YourRunnable> queue;
  public YourRunnable(BlockingQueue<YourRunnable> queue){
    this.queue = queue;
  }
  public void run{
      // Your Code...
      // Finished Processing
      queue.add(this);
  }
}
public class ThreadWorkder implements Runnable { 
  private final BlockingQueue<YourRunnable> queue;
  ThreadWorker(BlockingQueue<YourRunnable> queue){
    this.queue = queue;
  }
  public void run{
    while(queue.take()){
       (new Thread(new YourRunnable(queue))).start();
    }
  }
  // general main method
  public static void main(String [] args){
    BlockingQueue<YourRunnable> queue = new LinkedBlockingQueue<YourRunnable>();
    ThreadWorker worker = new ThreadWorker(queue);
    Thread(worker).start();
    for (int i = 0; i < 100; i++){
      (new Thread(new YourRunnable(queue))).start();
    }
  }
}
不再见 2024-11-05 02:21:12

使用集合而不是数组。当线程完成时,让它们从数组中删除自己。像这样的事情:

public class Foo {
  Vector<Thread> threads = new Vector<Thread>(); //Vector is threadsafe

  public ensureThreadCount(int count) {
    while (threads.size() < count) {
      Thread t = new AweseomeThread(threads);
      threads.add(t);
      t.start();
    }
  }
}

public class AwesomeThread {
  Collection threads;
  public AwesomeThread(Collection threads) {
    this.threads = threads;
  }

  public void run() {
    try {
      // do stuff
    } catch (Throwable t) {
    } finally {
      threads.remove(this);
    }
  }
}

然后,让你的工作人员调用 Foo.ensureThreadCount()。

Use a collection instead of an array. As the threads are completed, have them remove themselves from the array. Something like this:

public class Foo {
  Vector<Thread> threads = new Vector<Thread>(); //Vector is threadsafe

  public ensureThreadCount(int count) {
    while (threads.size() < count) {
      Thread t = new AweseomeThread(threads);
      threads.add(t);
      t.start();
    }
  }
}

public class AwesomeThread {
  Collection threads;
  public AwesomeThread(Collection threads) {
    this.threads = threads;
  }

  public void run() {
    try {
      // do stuff
    } catch (Throwable t) {
    } finally {
      threads.remove(this);
    }
  }
}

Then, have your worker just call Foo.ensureThreadCount().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文