【问题标题】:Delphi firemonkey android multithreadingDelphi firemonkey android 多线程
【发布时间】:2016-02-06 19:55:48
【问题描述】:

我尝试使用来自 multithread 的方法使用 delphi firemonkey 为 android 平台创建多线程线程

它不起作用,有什么方法可以创建这样的工作线程吗?

谢谢。

【问题讨论】:

标签: android multithreading delphi firemonkey


【解决方案1】:

您可以使用并行编程库,这里使用创建线程的任务是一个快速示例

uses: System.Threading
var
    Mythreadtask : ITask;

procedure createthreads;
begin
    if Assigned(Mythreadtask) then
    begin
        if Mythreadtask.Status = TTaskStatus.Running then
        begin
        //If it is already running don't start it again
            Exit;
        end;
    end;
    Mythreadtask := TTask.Create (procedure ()
    var s : String //Create Thread var here
    begin
    //Do all logic in here
    //If you need to do any UI related modifications
     TThread.Synchronize(TThread.CurrentThread,procedure()
        begin 
            //Remeber to wrap them inside a Syncronize
        end);
    end);
// Ensure that objects hold no references to other objects so that they can be freed, to avoid memory leaks. 
end;

添加:

如果你想在你的评论中点赞想要 5 个工作线程,你可以使用一系列任务,这是从并行编程库文档中提取的

procedure createthreads;
var 
    tasks: array of ITask; //Declare your dynamic array of ITask 
    value: Integer; 
begin 
Setlength (tasks ,2); // Set the size of the Array (How many threads you want to use in your case this would be 5)
value := 0; 

//This the 1st thread because it is the thread located in position 1 of the array of tasks
tasks[0] := TTask.Create (procedure () 
begin 
    sleep (3000); // 3 seconds 
    TInterlocked.Add (value, 3000); 
 end); 
 tasks[0].Start;// until .Start is called your task is not executed
 // this starts the thread that is located in the position [0] of tasks 

 //And this is the 2nd thread 
 tasks[1] := TTask.Create (procedure () 
 begin 
     sleep (5000); // 5 seconds 
     TInterlocked.Add (value, 5000);
 end); 
 tasks[1].Start;// and the second thread is started 
 TTask.WaitForAll(tasks); {This will have the mainthread wait for all the 
                 {threads of tasks to finish before moving making sure that when the
                 showmessage All done is displayed all the threads are done} 
 ShowMessage ('All done: ' + value.ToString); 
 end;

【讨论】:

  • 这就是我要找的,谢谢@peter-john jansen,还有一个问题,例如我需要 5 个不同的工作线程,我只需创建 5 个过程 createthreads;例如过程 createthreads1;过程创建线程2;等等..?
  • 创建一个任务数组,然后您可以轻松启动和停止它们,我在评论中分享的链接显示了如何创建一个任务数组并使用它们
  • 嗨@SuperBug,如果这个答案已经解决了你的问题,请考虑点击复选标记接受它。这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己提供了一些声誉。没有义务这样做。
  • 这可能是他的错,他忘记将此标记为答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-08
  • 1970-01-01
  • 2016-03-18
  • 1970-01-01
  • 2018-09-09
  • 2014-02-08
  • 2017-07-30
相关资源
最近更新 更多