在Swift / Objective

编程入门 行业动态 更新时间:2024-10-05 17:16:02
本文介绍了在Swift / Objective-C中实现下一个线程解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我开始学习 iOS 的编程,我想了解如何在 Swift中使用线程实现下一个 Java 函数,以及 Objective-C (在我的应用中,我也有一些使用此语言的代码)

I started to learn programming for iOS and I want to find out how to implement next Java functions with threads in Swift, and also in Objective-C (in my app I have some code using this language too)

Java线程(用于Android应用程序)

1)等待两个或多个线程完成

1) Wait for two or more threads to finished

final CountDownLatch latch = new CountDownLatch(2); // start thread #1 new Thread(new Runnable() { @Override public void run() { // do some work latch.countDown(); } }).start(); // start thread #2 new Thread(new Runnable() { @Override public void run() { // do some work latch.countDown(); } }).start(); // wait for 2 threads to end (finish) try { latch.await(); } catch (InterruptedException e) { // } // two threads are finished // do other work

2)仅当前一个线程此时完成或任何线程尚未启动时才启动新线程( mThread == null )

2) Start new thread only if previous one was finished at this time or any thread wasn't started yet (mThread == null)

private Thread mThread = null; // class field

// check if thread has completed execution if ((mThread != null && mThread.getState() == Thread.State.TERMINATED) || mThread == null) { mThread = new Thread(new Runnable() { @Override public void run() { // do some work } }); mThread.start(); }

推荐答案

我对第一个的回答( 1)解决方案(等待所有线程完成执行):

my answer for the first (1) solution (wait until all threads finish its execution):

dispatch_group_t group = dispatch_group_create(); dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ { // block1 NSLog(@"Task Block1"); [NSThread sleepForTimeInterval:6.0]; NSLog(@"Task Block1 End"); }); dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ { // block2 NSLog(@"Task Block2"); [NSThread sleepForTimeInterval:5.0]; NSLog(@"Task Block2 End"); }); dispatch_group_wait(group, DISPATCH_TIME_FOREVER); // blocks current thread

第二个解决方案(2)

我没有找到像 isRunning 这样的GCD方法,所以我只使用布尔变量

I didn't find for GCD method like isRunning, so I just use Boolean variable

在启动异步任务集变量isRunning为true之前 ... ... 当异步任务完成时我们可以使用下一个回调:

before starting async task set variable isRunning to true ... ... when async task is finished we can use next callback:

dispatch_group_notify(_signInitThread, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ { isRunning = false; });

更多推荐

在Swift / Objective

本文发布于:2023-11-28 04:21:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1640938.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Swift   Objective

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!