Java多线程似乎没有正确工作 [英] Java Multithreading doesn't seem to be correctly working

查看:190
本文介绍了Java多线程似乎没有正确工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个处理某事的类。我正在尝试并行运行这个类的多个实例。

I have a class which processes something. I'm trying to run a number of instances of this class in parallel.

但是,我不确定是否在 TaskManager.startAll( ),当我调用 r.go()时,是否会导致r开始在自己的线程中运行,或者在主线程内运行?

However, I'm not sure if in TaskManager.startAll(), when I call r.go(), whether this would cause r to start running in its own thread, or within the main thread?

我得到的总执行时间似乎非常高,尽管我尝试优化,但似乎没有任何效果。此外,如果我在Netbeans中的项目上运行一个分析器,它会显示所有线程都处于休眠状态。所以我想知道我做错了什么?

The total execution time that I'm getting seems to be very high, and despite my attempts at optimizing, nothing seems to be having any effect. Also, if I run a profiler on my project in Netbeans, it shows all the threads as sleeping. So I'd like to know if I'm doing something wrong?

这是班级的结构:

public class TaskRunner implements Runnable {
   private boolean isRunning = false;
   public void run() {
        while(true) {
            while (! running) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            process();
        }
    }

    public void go() {
       isRunning = true;
    }

    public void stop() {
       isRunning = false;
    }

    private void process() {
       //Do some number crunching and processing here
    }
}

以下是这些运行/管理的方式:

Here's how these are being run / managed:

public class TaskManager {
     private ArrayList<TaskRunner> runners = new ArrayList<>();
     public TaskManager() {
        for (int i = 0; i < 10; i++) {
            TaskRunner r = new TaskRunner();
            new Thread(r).start();
            runners.add(r);
        }
     }

     public void startAll() {
        for (TaskRunner r : runners) {
           r.go();
         }
     }
}


推荐答案

确实,你并没有做得对。如果要创建多线程Java应用程序,首先要使用 java.util.concurrent 包。

Indeed, you are not "doing it right." If you want to create a multi-threaded Java application, the place to start is with the java.util.concurrent package.

从代码中可以看出,您希望并行运行10个任务。我假设在数字运算和处理之后,你需要聚合结果并在主线程中对它们做一些事情。为此, ExecutorService invokeAll()方法效果很好。

It appears from your code that you want to run ten tasks in parallel. I assume that after "number crunching and processing," you'll want to aggregate the results and do something with them in the main thread. For this, the invokeAll() method of ExecutorService works well.

首先,实现 Callable 来完成您在 process()方法中显示的工作。

First, implement Callable to do the work you show in your process() method.

final class YourTask implements Callable<YourResults> {

  private final YourInput input;

  YourTask(YourInput input) {
    this.input = input;
  }

  @Override
  public YourResults call() 
    throws Exception 
  {
    /* Do some number crunching and processing here. */
    return new YourResults(...);
  }

}

然后创建任务并运行它们。这将取代您的 main()方法:

Then create your tasks and run them. This would take the place of your main() method:

Collection<Callable<YourResults>> tasks = new List<>(inputs.size());
for (YourInput i : inputs) 
  tasks.add(new YourTask(i));
ExecutorService workers = Executors.newFixedThreadPool(10);
/* The next call blocks while the worker threads complete all tasks. */
List<Future<YourResult>> results = workers.invokeAll(tasks);
workers.shutdown();
for (Future<YourResult> f : results) {
  YourResult r = f.get();
  /* Do whatever it is you do with the results. */
  ...
}

这篇关于Java多线程似乎没有正确工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆