您的位置:首页 > 其它

多线程(1) pthread(可无视) 2.NSThread(静态方法使用居多)

2015-04-25 17:20 483 查看
iOS中多线程的实现方案

1.pthread

2.NSThread

3.GCD

4.NSOperation

线程的状态



1.pthread(几乎不用)

一套通用的多线程API
适用于Unix\Linux\Windows等系统
跨平台\可移植
使用难度大

语言: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(大多使用静态方法)

使用更加面向对象
简单易用,可直接操作线程对象
语言:OC
线程生命周期:程序员管理

- (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


原子和非原子属性

OC在定义属性时有nonatomic和atomic两种选择
atomic:原子属性,为setter方法加锁(默认就是atomic)
nonatomic:非原子属性,不会为setter方法加锁

@autoreleasepool

iOS开发中的内存管理
(1)在iOS开发中,并没有JAVA或C#中的垃圾回收机制
(2)使用ARC开发,只是在编译时,编译器会根据代码结构自动添加了retain、release和autorelease

自动释放池的工作原理
(1)标记为autorelease的对象在出了作用域范围后,会被添加到最近一次创建的自动释放池中
(2)当自动释放池被销毁或耗尽时,会向自动释放池中的所有对象发送release消息
每个线程都需要有@autoreleasepool,否则可能会出现内存泄漏,但是使用NSThread多线程技术,并不会为后台线程创建自动释

线程间通信

线程间通信的体现
1个线程传递数据给另1个线程
在1个线程中执行完特定任务后,转到另1个线程继续执行任务

线程间通信常用方法
- (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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: