一、基本使用

1.多线程的优缺点

多线程的优点
能适当提高程序的执行效率
能适当提高资源利用率(CPU、内存利用率)
多线程的缺点
开启线程需要占用一定的内存空间(默认情况下,主线程占用1M,子线程占用512KB),如果开启大量的线程,会占用大量的内存空间,降低程序的性能
线程越多,CPU在调度线程上的开销就越大
程序设计更加复杂:比如线程之间的通信、多线程的数据共享
 
 
2.多线程在iOS开发中的应用
什么是主线程
一个iOS程序运行后,默认会开启1条线程,称为“主线程”或“UI线程”
 
主线程的主要作用
显示\刷新UI界面
处理UI事件(比如点击事件、滚动事件、拖拽事件等)
 
主线程的使用注意
别将比较耗时的操作放到主线程中
耗时操作会卡住主线程,严重影响UI的流畅度,给用户一种“卡”的坏体验
 
 
 //
// ViewController.m
// IOS_0116_NSThread
//
// Created by ma c on 16/1/16.
// Copyright (c) 2016年 博文科技. All rights reserved.
// #import "ViewController.h"
#import <pthread.h> /*
线程的实现方案
pthread
NSThread
GCD
NSOperation
*/
@interface ViewController () @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; //[self pthread]; }
#pragma mark - 创建线程NSThread
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// [self createThread1];
// [self createThread2];
[self createThread3]; }
#pragma mark - 创建线程3
- (void)createThread3
{
//隐式创建线程
[self performSelector:@selector(download:) withObject:@"http:www.bowen.cn"];
[self download:@"http:www.bowen.cn"]; [self performSelectorInBackground:@selector(download:) withObject:@"http:www.bowen.cn"]; [self performSelector:@selector(download:) onThread:[NSThread mainThread] withObject:@"http:www.bowen.cn" waitUntilDone:nil]; } #pragma mark - 创建线程2
- (void)createThread2
{
//创建后并启动线程
[NSThread detachNewThreadSelector:@selector(download:) toTarget:self withObject:@"http:www.bowen.cn"];
}
- (void)download:(NSString *)url
{
NSLog(@"\ndownload----%@",[NSThread mainThread]); NSLog(@"\ndownload----%@----%@",url,[NSThread currentThread]);
} #pragma mark - 创建线程1
//启动线程 - 进入就绪状态 -(CPU调度当前线程)- 运行状态 - 线程任务完毕,自动进入死亡状态
// -调用sleep方法或者等待同步锁 - 阻塞状态
- (void)createThread1
{
//创建线程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(download) object:nil];
//设置线程的名字
thread.name = @"下载线程";
//当前线程是否是主线程
[thread isMainThread];
//启动线程
[thread start]; //判断当前方法是否是在主线程主线程中执行
[NSThread isMainThread];
} - (void)download
{
NSLog(@"\ndownload----%@",[NSThread mainThread]); //阻塞线程
[NSThread sleepForTimeInterval:];
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:]]; NSLog(@"\ndownload----%@",[NSThread currentThread]); //强制停止线程
[NSThread exit];
NSLog(@"\ndownload----%@",@"exit");
} #pragma mark - pthread
- (void)pthread
{
NSLog(@"\nviewDidLoad-------%@",[NSThread currentThread]); //创建线程
pthread_t myRestrict;
pthread_create(&myRestrict, NULL, run, NULL);
} void *run(void *data)
{
NSLog(@"\nrun-------%@",[NSThread currentThread]); return NULL;
} @end

二、线程安全

 //
// ViewController.m
// IOS_0117_线程的安全隐患
//
// Created by ma c on 16/1/17.
// Copyright (c) 2016年 博文科技. All rights reserved.
// #import "ViewController.h" @interface ViewController () @property (nonatomic, strong) NSThread *thread1;
@property (nonatomic, strong) NSThread *thread2; //剩余票数
@property (nonatomic, assign) int leftTicketCount; @end @implementation ViewController
/*
资源共享
一块资源可能会被多个线程共享,也就是多个线程可能会访问[同一块资源] 比如多个线程访问同一个对象、同一个变量、同一个文件 当多个线程访问同一块资源时,很容易引发[数据错乱和数据安全]问题 */ - (void)viewDidLoad {
[super viewDidLoad]; self.leftTicketCount = ; self.thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
self.thread1.name = @"1号窗口";
self.thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
self.thread2.name = @"2号窗口"; } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.thread1 start];
[self.thread2 start];
}
/*
互斥锁使用格式
@synchronized(锁对象) { // 需要锁定的代码 }
注意:锁定1份代码只用1把锁,用多把锁是无效的 互斥锁的优缺点
优点:能有效防止因多线程抢夺资源造成的数据安全问题
缺点:需要消耗大量的CPU资源 互斥锁的使用前提:多条线程抢夺同一块资源 相关专业术语:线程同步
线程同步的意思是:多条线程在同一条线上执行(按顺序地执行任务)
互斥锁,就是使用了线程同步技术 */
- (void)saleTicket
{
while () { @synchronized(self){ //开始枷锁 小括号里面放的是锁对象
int count = self.leftTicketCount;
if (count>) {
self.leftTicketCount = count -;
NSLog(@"%@卖了一张票,剩余%d张票",[NSThread currentThread].name, self.leftTicketCount);
}else{
return; //退出循环 break
} }//解锁 }
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} @end

三、线程间通信

 //
// ViewController.m
// IOS_0117_线程间通信
//
// Created by ma c on 16/1/17.
// Copyright (c) 2016年 博文科技. All rights reserved.
// #import "ViewController.h" @interface ViewController () @property (nonatomic, strong) UIImageView *imgView; @end @implementation ViewController /*
什么叫做线程间通信
在1个进程中,线程往往不是孤立存在的,多个线程之间需要经常进行通信 线程间通信的体现
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; */
- (void)viewDidLoad {
[super viewDidLoad]; self.imgView = [[UIImageView alloc] initWithFrame:CGRectMake(, , , )];
//self.imgView.image = [UIImage imageNamed:@"1.png"];
self.imgView.backgroundColor = [UIColor cyanColor];
[self.view addSubview:self.imgView]; } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self performSelectorInBackground:@selector(downloadPicture) withObject:nil]; } - (void)downloadPicture
{ NSLog(@"\ndownload----%@",[NSThread currentThread]);
//1.图片地址
NSString *urlStr = @"1.png";
//NSURL *url = [NSURL URLWithString:urlStr];
//2.根据地址下载图片的二进制数据
//NSData *data = [NSData dataWithContentsOfURL:url];
//3.设置图片
UIImage *image = [UIImage imageNamed:urlStr];
//self.imgView.image = [UIImage imageWithData:data];
//4.回到主线程,刷新UI界面(为了线程安全)
[self performSelectorOnMainThread:@selector(downloadFinished:) withObject:image waitUntilDone:YES];
}
- (void)downloadFinished:(UIImage *)image
{ NSLog(@"\ndownloadFinished----%@",[NSThread currentThread]);
self.imgView.image = image; }
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} @end

iOS UI-线程(NSThread)及其安全隐患与通信的更多相关文章

  1. IOS UI多线程 NSThread 下载并显示图片到UIImageView

    效果图 @property (weak,nonatomic)IBOutletUILabel *downLabelInfo; @property (weak,nonatomic)IBOutletUIIm ...

  2. iOS UI异步更新:dispatch_async 与 dispatch_get_global_queue 的使用方法

    GCD (Grand Central Dispatch) 是Apple公司开发的一种技术,它旨在优化多核环境中的并发操作并取代传统多线程的编程模式. 在Mac OS X 10.6和IOS 4.0之后开 ...

  3. iOS-线程&&进程的深入理解

    进程基本概念 进程就是一个正在运行的一个应用程序; 每一个进度都是独立的,每一个进程均在专门且手保护的内存空间内; iOS是怎么管理自己的内存的,见博客:博客地址 在Linux系统中,想要新开启一个进 ...

  4. iOS GCD NSOperation NSThread等多线程各种举例详解(拷贝)

    2年多的iOS之路匆匆而过,期间也拜读来不少大神的博客,近来突然为自己一直做伸手党感到羞耻,是时候回馈社会.回想当年自己还是小白的时候,照着一些iOS多线程教程学,也只是照抄,只知其然.不知其所以然. ...

  5. iOS多线程开发--NSThread NSOperation GCD

    多线程 当用户播放音频.下载资源.进行图像处理时往往希望做这些事情的时候其他操作不会被中 断或者希望这些操作过程中更加顺畅.在单线程中一个线程只能做一件事情,一件事情处理不完另一件事就不能开始,这样势 ...

  6. IOS任务管理之NSThread使用

    前言: 无论是Android还是IOS都会使用到多任务,多任务的最小单元那就是线程,今天学习总结一下IOS的NSThread使用. NSThread使用? 第一种方式实例化 //selector :线 ...

  7. iOS GCD NSOperation NSThread等多线程各种举例详解

    废话就不多说,直接上干货.如下图列举了很多多线程的知识点,每个按钮都写有对应的详细例子,并对运行结果进行分析,绝对拿实践结果来说话.如果各位道友发现错误之处还请指正.附上demo下载地址

  8. iOS:多线程NSThread的详细使用

    NSThread具体使用:直接继承NSObject NSThread:. 优点:NSThread 是轻量级的,使用简单 缺点:需要自己管理线程的生命周期.线程同步.线程同步对数据的加锁会有一定的系统开 ...

  9. iOS开发 - 线程与进程的认识与理解

    进程: 进程是指在系统中正在运行的一个应用程序,比如同时打开微信和Xcode,系统会分别启动2个进程; 每个进程之间是独立的,每个进程均运行在其专用且受保护的内存空间内; 线程: 一个进程要想执行任务 ...

随机推荐

  1. sosi-statistics

    set echo offset scan onset lines 150set pages 66set verify offset feedback offset termout offcolumn ...

  2. 高频访问IP弹验证码架构图 让被误伤的用户能及时自行解封的策略

    高频访问IP限制 --Openresty(nginx + lua) [反爬虫之旅] - Silbert Monaphia - CSDN博客 https://blog.csdn.net/qq_29245 ...

  3. java 并查集

    并查集代码 并查集优化⼀ 并查集优化⼆ 实战题⽬目1. https://leetcode.com/problems/number-of-islands/2. https://leetcode.com/ ...

  4. L​i​n​u​x​下​的​D​a​e​m​o​n​简​介(转)

    add by zhj: 接触这个概念也有段时间了,但一直没搞明白,今天总算明白了. 原文:http://wenku.baidu.com/link?url=FEJeQ0J45YaFXansxT2GVVB ...

  5. mysql 约束条件 unique key 唯一的键

    如果不设置unique 会出现两条相同的记录 mysql)); Query OK, rows affected (0.01 sec) mysql ,,'mike'); Query OK, rows a ...

  6. android gson使用

    第一步注册:  compile 'com.google.code.gson:gson:2.6.2' 第二步初始化: Gson gson = new GsonBuilder() .setLenient( ...

  7. Redis持久化磁盘IO方式及其带来的问题

    有Redis线上运维经验的人会发现Redis在物理内存使用比较多,但还没有超过实际物理内存总容量时就会发生不稳定甚至崩溃的问题 一.对Redis持久化的探讨与理解 redis是一个支持持久化的内存数据 ...

  8. (转)《SSO CAS单点系列》之 15分钟让你了解SSO技术到底是个什么鬼!

    Web应用系统的演化总是从简单到复杂,从单功能到多功能模块再到多子系统方向发展. .当前的大中型Web互联网应用基本都是多系统组成的应用群,由多个web系统协同为用户提供服务. 多系统应用群,必然意味 ...

  9. 在线学习--online learning

    在线学习 online learning Online learning并不是一种模型,而是模型的训练方法.能够根据线上反馈数据,实时快速的进行模型调优,使得模型能够及时反映线上的变化,提高线上预测的 ...

  10. 两个栈实现队列&两个栈实现队列

    为说明思想,假设队列.栈都很大,不会出现满的情况. 1. 两个栈实现队列 //前提已知: struct Stack { int top; //栈顶指针 int stacksize;//栈的大小 int ...