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

13 篇文章 0 订阅

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


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dwt1220

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值