iOS中多线程的实现方案
1.pthread
2.NSThread
3.GCD
4.NSOperation
线程的状态
1.pthread(几乎不用)
语言:C
线程生命周期:程序员管理
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
pthread_t thread; //创建线程
NSString *str = @"hello"; //创建参数
//开启一个线程
//第一个参数 线程编号的地址
//第二个参数 线程的属性
//第三个参数 线程要执行的函数(函数指针)(第三个参数可以,demo,*demo, 一般用&demo)
//第四个参数 线程要执行的函数的参数
int result = pthread_create(&thread, NULL, &demo, (__bridge void *)(str));
//__bridge oc类型到c语言类型的一个转换
// void *p = (__bridge void *)(str);
NSLog(@"over %d",result);
}
//线程要执行的函数 传参数
void *(demo)(void *param){
NSString *str = (__bridge NSString *)(param);
NSLog(@"%@",str);
return NULL;
}
2.NSThread(大多使用静态方法)
线程生命周期:程序员管理
- (void)run:(NSString *)param
{
NSThread *current = [NSThread currentThread];
//for (int i = 0; i<10000; i++) {
NSLog(@"%@----run---%@", current, param);
//}
}
/**
* 方式1
* NSThread的创建方式
* 隐式创建线程, 并且直接(自动)启动
*/
- (void)threadCreate3
{
// 在后台线程中执行 === 在子线程中执行
[self performSelectorInBackground:@selector(run:) withObject:@"abc参数"];
}
/**
* 方式2
* NSThread的创建方式
* 创建完线程直接(自动)启动
*/
- (void)threadCreate2
{
[NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"我是参数"];
}
/**
* 方式3
* NSThread的创建方式
* 1> 先创建初始化线程
* 2> start开启线程
*/
- (void)threadCreate
{
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"哈哈"];
thread.name = @"线程A";
// 开启线程
[thread start];
NSThread *thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"哈哈"];
thread2.name = @"线程B";
// 开启线程
[thread2 start];
}
NSThread 方法
+ (NSThread *)mainThread; //获得主线程
- (BOOL)isMainThread; //是否为主线程
+ (BOOL)isMainThread; //是否为主线程
// 1.获得当前的线程
NSThread *current = [NSThread currentThread];
- (void)start;
// 开启线程
[self.thread start];
// 进入就绪状态 ->运行状态。当线程任务执行完毕,自动进入死亡状态
+ (void)sleepUntilDate:(NSDate*)date;
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;
// 进入阻塞状态
+ (void)exit;
// 进入死亡状态
注意:一旦线程停止(死亡)了,就不能再次开启任务
- (void)test
{
NSLog(@"test - 开始 - %@", [NSThread currentThread].name);
// 阻塞状态
[NSThread sleepForTimeInterval:5];
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:5.0];
[NSThread sleepUntilDate:date];
for (int i = 0; i<1000; i++) {
NSLog(@"test - %d - %@", i, [NSThread currentThread].name);
if (i == 50) {
// 强制停止线程
[NSThread exit];
}
}
NSLog(@"test - 结束 - %@", [NSThread currentThread].name);
}
+ (double)threadPriority;
+ (BOOL)setThreadPriority:(double)p;
- (double)threadPriority;
- (BOOL)setThreadPriority:(double)p;
调度优先级的取值范围是0.0 ~ 1.0,默认0.5,值越大,优先级越高
自己开发时,不要修改优先级,否则一旦出现“优先级反转”会非常麻烦
- (void)setName:(NSString *)n;
- (NSString*)name;
self.thread = [[NSThread alloc] initWithTarget:self selector:@selector(test) object:nil];
self.thread.name = @"线程A";
@synchronized(锁对象) { // 需要锁定的代码 }
注意:锁定1份代码只用1把锁,用多把锁是无效的
#import "HMViewController.h"
@interface HMViewController ()
/** 剩余票数 */
@property (nonatomic, assign) int leftTicketsCount;
@property (nonatomic, strong) NSThread *thread0;
@property (nonatomic, strong) NSThread *thread1;
@property (nonatomic, strong) NSThread *thread2;
@end
@implementation HMViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// 默认有100张
self.leftTicketsCount = 100;
// 开启多条线程同时卖票
self.thread0 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
self.thread0.name = @"售票员 A";
// self.thread0.threadPriority = 0.0;
self.thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
self.thread1.name = @"售票员 B";
// self.thread1.threadPriority = 1.0;
self.thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
self.thread2.name = @"售票员 C";
// self.thread2.threadPriority = 0.0;
}
/**
* 卖票
*/
- (void)saleTicket
{
while (1) {
@synchronized(self) { // 加锁(只能用一把锁)
// 1.先检查票数
int count = self.leftTicketsCount;
if (count > 0) {
// 暂停
// [NSThread sleepForTimeInterval:0.0002];
// 2.票数 - 1
self.leftTicketsCount = count - 1;
NSThread *current = [NSThread currentThread];
NSLog(@"%@ 卖了一张票, 剩余%d张票", current.name, self.leftTicketsCount);
} else {
// 退出线程
[NSThread exit];
}
} // 解锁
}
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.thread0 start];
[self.thread1 start];
[self.thread2 start];
}
@end
原子和非原子属性
@autoreleasepool
线程间通信
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;
#import "HMViewController.h"
@interface HMViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end
@implementation HMViewController
- (void)viewDidLoad
{
[super viewDidLoad];
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(110, 56, 100, 100)];
[self.view addSubview:imageView];
self.imageView = imageView;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// 在子线程中调用download方法下载图片
[self performSelectorInBackground:@selector(download) withObject:nil];
}
/**
* 下载图片 : 子线程
*/
- (void)download
{
// 1.根据URL下载图片
NSURL *url = [NSURL URLWithString:@"http://news.baidu.com/z/resource/r/image/2014-06-22/2a1009253cf9fc7c97893a4f0fe3a7b1.jpg"];
NSLog(@"-------begin");
NSData *data = [NSData dataWithContentsOfURL:url]; // 这行会比较耗时
NSLog(@"-------end");
UIImage *image = [UIImage imageWithData:data];
// 2.回到主线程调用 setImage: 方法
[self.imageView performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:NO];
// setImage: 1s
[self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];
// [self performSelectorOnMainThread:@selector(settingImage:) withObject:image waitUntilDone:NO];
}
/**
* 设置(显示)图片: 主线程
*/
//- (void)settingImage:(UIImage *)image
//{
// self.imageView.image = image
//}
@end