简体   繁体   English

适用于 Java/Android 的 TPL 等效项

[英]TPL Equivalent for Java/Android

I'm curious to know if there's something similar to the Task Parallel Library from C# in Java and/or the Android SDK. I'm curious to know if there's something similar to the Task Parallel Library from C# in Java and/or the Android SDK. Coming from a C# background, we're taught that making a new thread is a relatively heavyweight operation, and are instructed to use the threadpool, or more recently, Tasks.来自 C# 背景,我们被告知创建一个新线程是一个相对重量级的操作,并被指示使用线程池,或者最近的任务。

So in my mind, the level of abstraction that Tasks bring would be ideal... is there anything like that, or even the threadpool?所以在我看来,Tasks 带来的抽象级别是理想的……有没有类似的东西,甚至是线程池? or does it all just involve making a new Thread or making my own threadpool还是这一切都只涉及制作一个新线程或制作我自己的线程池

Sure it does.当然可以。 You can read more about it here: Executors你可以在这里阅读更多关于它的信息: Executors

Also, you could overview the whole concurrency topic at the same page: Concurrency此外,您可以在同一页面上概述整个并发主题: 并发

I think that the java.util.concurrent package has most of the classes/functionality you are looking for.我认为java.util.concurrent package 具有您正在寻找的大部分类/功能。

Specifically, take a look at these:具体来说,看看这些:

  1. ThreadPoolExecutor 线程池执行器
  2. Executors 执行者
  3. CompletionService 完成服务

According to Java developers, Java concurrency programming should be moving towards the usage of the new Concurrency API.根据 Java 开发人员的说法,Java 并发编程应该朝着使用新的并发 API 的方向发展。

Check: http://download.oracle.com/javase/1.5.0/docs/guide/concurrency/index.html检查: http://download.oracle.com/javase/1.5.0/docs/guide/concurrency/index.html

Android has support for Javas concurrency library but you should look into AsyncTask which supports running operations on both on the UI thread and in the background. Android 支持 Java 并发库,但您应该查看支持在 UI 线程和后台运行操作的AsyncTask

Here is an a short example of a task:下面是一个简短的任务示例:

private class CharCountTask extends AsyncTask<String, Integer, Long> {
  protected Long doInBackground(String... in) {
    long result = 0;
    for(int i=0,n=in.length; i<n; i++) {
      result += in[i].length();
      publishProgress((int) (i / (double) count) * 100);
    }
    return result;
  }

  protected void onProgressUpdate(Integer... progress) {
    // update progress here
    updateProgressBar(progress[0]);
  }

  protected void onPostExecute(Long result) {
    // update the UI here
    setTotalChars(result);
  }
}

To use it:要使用它:

new CharCountTask().execute("first", "second", "third");

Look at the Task4Java framework at https://github.com/dtag-dbu/task4java/ .查看位于https://github.com/dtag-dbu/task4java/的 Task4Java 框架。

This framework was build on standard Java libraries and runs also on Android.该框架建立在标准 Java 库之上,并且也在 Android 上运行。 Currently we are creating a sample application to show the power of this framework.目前我们正在创建一个示例应用程序来展示这个框架的强大功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM