博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
多线程(二)--NSThread基本使用
阅读量:4653 次
发布时间:2019-06-09

本文共 1965 字,大约阅读时间需要 6 分钟。

iOS多线程实现方案

pthread:

C语言,生命周期需要管理,
一套通用多线程API
试用Unix\Linux\Windows系统
跨平台\可移植
使用难度大

NSThread:

OC语言,生命周期需要管理
面向对象
可直接操作线程对象

GCD:(常用)

C语言,自动管理生命周期
旨在替代NSThread等多线程技术
充分利用设备多核

NSOperation:(常用)

OC语言,自动管理线程生命周期
基于GCD
比GCD多些简单实用功能
更面向对象

举例:
pthread

#import <pthread.h>

void *run(void *data)

{
for (int i = 0; i<10000; i++) {
NSLog(@"touchesBegan----%d-----%@", i, [NSThread currentThread]);
}
return NULL;
}

 

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{
// 创建线程
pthread_t myRestrict;
pthread_create(&myRestrict, NULL, run, NULL);
}

NSThread:

一个NSThread对象代表一条线程

创建、启动线程

NSThread *current = [NSThread currentThread];

线程调度优先级

+ (double)threadPriority;
+ (BOOL)setThreadPriority:(double)p;
- (double)threadPriority;
- (BOOL)setThreadPriority:(double)p;
优先级范围:0.0~1.0
默认0.5
值越大优先级越高

线程名称

- (void)setName:(NSString *)n;
- (NSString *)name;

3种创建线程方式

/**

* 创建线程的方式3
*/

- (void)createThread3

{

// 这2个不会创建线程,在当前线程中执行
// [self performSelector:@selector(download:) withObject:@"http://c.gif"];
// [self download:@"http://c.gif"];
[self performSelectorInBackground:@selector(download:) withObject:@"http://c.gif"];
}

/**
* 创建线程的方式2
*/

- (void)createThread2

{
[NSThread detachNewThreadSelector:@selector(download:) toTarget:self withObject:@"http://a.jpg"];
}

/**
* 创建线程的方式1
*/

- (void)createThread1

{
// 创建线程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(download:) object:@"http://b.png"];
thread.name = @"下载线程";
// 启动线程(调用self的download方法)
[thread start];
}

- (void)download:(NSString *)url

{

NSLog(@"下载东西---%@---%@", url, [NSThread currentThread]);
}

线程睡眠(阻塞线程)
// 睡眠5秒钟

[NSThread sleepForTimeInterval:5];

// 3秒后的时间

NSDate *date = [NSDate dateWithTimeIntervalSinceNow:3];

[NSThread sleepUntilDate:date];

启动线程
- (void)start;
就绪--运行--执行完毕死亡

阻塞(暂停)线程

+ (void)sleepUntilDate:(NSDate *)date;
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;
进入阻塞状态

强制停止线程

+ (void)exit;

线程死了之后,不可以重新start

转载于:https://www.cnblogs.com/fangchun/p/4684327.html

你可能感兴趣的文章
3月7日 ArrayList集合
查看>>
jsp 环境配置记录
查看>>
Python03
查看>>
LOJ 2537 「PKUWC2018」Minimax
查看>>
使用java中replaceAll方法替换字符串中的反斜杠
查看>>
Some configure
查看>>
流量调整和限流技术 【转载】
查看>>
1 线性空间
查看>>
VS不显示最近打开的项目
查看>>
DP(动态规划)
查看>>
chkconfig
查看>>
2.抽取代码(BaseActivity)
查看>>
夏天过去了, 姥爷推荐几套来自smashingmagzine的超棒秋天主题壁纸
查看>>
反射的所有api
查看>>
css 定位及遮罩层小技巧
查看>>
[2017.02.23] Java8 函数式编程
查看>>
sprintf 和strcpy 的差别
查看>>
JS中window.event事件使用详解
查看>>
ES6深入学习记录(一)class方法相关
查看>>
C语言对mysql数据库的操作
查看>>