在Swift / Objective-C中实现下一个线程解决方案

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

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

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

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

 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(); } 

对于2 ,我会使用串行队列:

 dispatch_queue_t myQueue; 

并按以下方式实现我的队列:

 myQueue = dispatch_queue_create("my_serial_queue", DISPATCH_QUEUE_SERIAL); dispatch_async(myQueue, ^{ for (int i = 0; i < 10000; i++) { usleep(100); } NSLog(@"Task 1 done"); }); dispatch_async(myQueue, ^{ NSLog(@"Task 2 done"); }); 

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

 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方法,所以我只使用布尔变量

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

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