一、基本使用

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. FW:stash install

    先下载破解安装包.http://pan.baidu.com/s/1mgumBbE 我的安装环境. 说明下,经过我的测试. 如果系统内存低于 512M, 就不要折腾了,非常卡. 推荐 2048M 内存. ...

  2. scribe、chukwa、kafka、flume日志系统对比

    scribe.chukwa.kafka.flume日志系统对比   1. 背景介绍许多公司的平台每天会产生大量的日志(一般为流式数据,如,搜索引擎的pv,查询等),处理 这些日志需要特定的日志系统,一 ...

  3. CRM - 起步

    一.crm简介 crm 客户关系管理软件 ( Customer Relationship Management ) 二.起步 models.py 表结构 from django.db import m ...

  4. What Powers Instagram: Hundreds of Instances, Dozens of Technologies(译文,转)

    add by zhj: 对译文略有修改.原文发表时,Instagram还没被Facebook收购,读完只感觉Instagram这三个后台工程师真牛逼. 三个人就可以搞定1400万注册用户.不过,另一方 ...

  5. Day05 xml详解

    day05总结 今日内容 XML语法 XML约束之DTD XML解析器介绍 XML解析之JAXP( DOM.SAX ) DOM4J Schema   一.XML语法 XML概述   1 什么是XML ...

  6. sql server 2008维护计划配置

    转自:https://blog.csdn.net/yunye114105/article/details/6594826 一:目标任务: 使用SQL Server 2008自带的维护计划自动备份数据库 ...

  7. python 面向对象 isinstance

    查看某个对象是否 这个类实例 是返回True 否则返回False class Foo(object): pass obj = Foo() class Boo(object): pass print(i ...

  8. 002-Spring Framework-Core-01-IoC容器

    一.概述 文章地址:https://docs.spring.io/spring/docs/5.0.6.RELEASE/spring-framework-reference/ 核心主要包括:IoC co ...

  9. js-jquery-从SweetAlert到SweetAlert2

    原文地址:https://github.com/limonte/sweetalert2/wiki/Migration-from-SweetAlert-to-SweetAlert2 1. IE supp ...

  10. react分享

    后台项目应用分享 后台项目应用分享 webpack + react + redux + antd 后台项目应用分享 策略篇 框架选择 组件化开发 组件?组件! CSS in JS下的样式开发思路 展示 ...