开启线程的四种方式:
pthread
NSThread
GCD
BSOperation
1.pthread
NSString *str = @"123456";
// 创建一条线程 自动执行的
// __bridge :桥接: OC数据类型传递给C语言的函数
//
// ARC:
// 混合开发: C 和 OC混合开发 内存管理.
// C语言没有自动内存管理 , OC有
// 编译器在编译的时候,会自动为OC代码添加自动内存管理操作
// C 需要手动管理内存
// 添加桥接目的 .就是告诉编译器,为OC添加自动内存管理操作
int result = pthread_create(&mythread, NULL, longTimeOperation, (__bridge void *)(str));
---------
// C语言的函数
// date:任意类型的参数
void *longTimeOperation(void *date)
{
// C语言转OC 也需要桥接
NSString *str = (__bridge NSString *)(date);
for (int i = 0; i < 100; i++) {
NSLog(@"%@----%d,%@",str,i,[NSThread currentThread]);
}
return NULL;
}
2.NSThread
// 开启一条线程
// 创建一个线程对象
//longTimeOperation:线程中要执行的方法
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(longTimeOperation) object:nil];
// 告诉CPU线程准备就绪,可以随时接受调度(执行).
[thread start];
----------------
// 创建线程
NSString *str = @"myThread";
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(downloadImage:) object:str];
// 设置线程的名字
thread.name = @"CZBK";
// 设置线程的优先级 0 ~ 1; 优先级反转.
thread.threadPriority = 0.5;
// 设置线程大小
thread.stackSize = 1024 *1024;
// 获得当前线程.
[NSThread currentThread];
// 获得主线程
// NSThread *main = [NSThread mainThread];
// 手动开启线程.
[thread start];
// 睡一会/ 阻塞 线程.
// 没有任何区别
[NSThread sleepForTimeInterval:3];
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:3];
[NSThread sleepUntilDate:date];
// 强制退出线程
[NSThread exit];回到主线程
----------------------线程通信
// 1.下载图片-子线程下载
[self performSelectorInBackground:@selector(downloadImage) withObject:nil];
// 线程间通信: 子线程下载图片/主线程更新UI
- (void)downloadImage
{
// 在这里执行下载图片操作之后,转到 主线程 显示图片
[self performSelectorOnMainThread:@selector(setupUIImage:) withObject:image waitUntilDone:NO];
}
// 显示图片-主线程
-(void)setupUIImage:(UIImage *)image
{
NSLog(@"----setupUIImage%@",[NSThread currentThread]);
self.imageView.image = image;
}
----------------------线程状态
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.thread = [[NSThread alloc] initWithTarget:self selector:@selector(longTimeOperation) object:nil];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(longTimeOperation) object:nil];
[self.thread start];
}
- (void)longTimeOperation
{
for (int i = 0; i < 100; i++) {
NSLog(@"-----%d %@",i,[NSThread currentThread]);
if (i == 50) {
NSLog(@"睡三秒"); //阻塞
[NSThread sleepForTimeInterval:3];
}
if (i == 80) {
// 强制退出线程
[NSThread exit];
}
}
}
----------------------线程安全
while (1) {
// self.tickts = self.tickts>0?self.tickts--:nil;
@synchronized(self){
if (self.tickts>0) {
self.tickts--;
NSLog(@"%@---剩余%lu",[NSThread currentThread],self.tickts);
}else{
return;
}
}
}