首先这是iOS开发中最不常用的创建线程的方式,则是使用C中线程库的API来创建线程。不过作为学习我们不妨多了解一下,对比观察观察。
话不多说,直接上代码。例子很简单也很狗血。从结果输出我们也可以看出异步多线程的特点就是线程是无序的执行的。
一、代码
#import <Foundation/Foundation.h>
#import <pthread.h>
void newThread();
void * run(void *param);
int main(int argc, const char * argv[]) {
@autoreleasepool {
newThread();
//主线程休眠2秒,因为主线程结束了子线程也就结束了啊!
[NSThread sleepForTimeInterval:2000];
}
return 0;
}
//pthread方式创建线程
void newThread()
{
//定义一个线程
pthread_t thread;
//创建一个线程
//参数一:创建线程的指针
//参数二:线程属性
//参数三:线程执行的函数的指针
//参数四:难道是传执行的函数的参数值?
pthread_create(&thread, NULL, run, NULL);
//创建第二个线程
pthread_t thread2;
pthread_create(&thread2, NULL, run, NULL);
}
void * run(void *param)
{
for (int i = 0; i < 1000; i++) {
NSLog(@"%zd------->%@", i, [NSThread currentThread]);
}
return NULL;
}
二、输出结果
从输出结果中我们可以看出,线程可能是交替运行也可能是不按顺序的(实际上就是无序的)。这里我们只是截取了部分输出信息而已。
2016-02-23 11:02:25.457 ThreadDemon[5739:385467] 0-------><NSThread: 0x100209ec0>{number = 2, name = (null)}
2016-02-23 11:02:25.458 ThreadDemon[5739:385466] 0-------><NSThread: 0x10020bc60>{number = 3, name = (null)}
2016-02-23 11:02:25.458 ThreadDemon[5739:385467] 1-------><NSThread: 0x100209ec0>{number = 2, name = (null)}
2016-02-23 11:02:25.458 ThreadDemon[5739:385466] 1-------><NSThread: 0x10020bc60>{number = 3, name = (null)}
2016-02-23 11:02:25.458 ThreadDemon[5739:385467] 2-------><NSThread: 0x100209ec0>{number = 2, name = (null)}
2016-02-23 11:02:25.458 ThreadDemon[5739:385466] 2-------><NSThread: 0x10020bc60>{number = 3, name = (null)}
2016-02-23 11:02:25.458 ThreadDemon[5739:385467] 3-------><NSThread: 0x100209ec0>{number = 2, name = (null)}
2016-02-23 11:02:25.458 ThreadDemon[5739:385466] 3-------><NSThread: 0x10020bc60>{number = 3, name = (null)}
2016-02-23 11:02:25.458 ThreadDemon[5739:385467] 4-------><NSThread: 0x100209ec0>{number = 2, name = (null)}
2016-02-23 11:02:25.458 ThreadDemon[5739:385466] 4-------><NSThread: 0x10020bc60>{number = 3, name = (null)}
2016-02-23 11:02:25.458 ThreadDemon[5739:385467] 5-------><NSThread: 0x100209ec0>{number = 2, name = (null)}
2016-02-23 11:02:25.458 ThreadDemon[5739:385466] 5-------><NSThread: 0x10020bc60>{number = 3, name = (null)}
......