在Swift / Objective-C中实现下一个线程解决方案 [英] Implementing next threading solutions in 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-C中实现下一个线程解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!