iOS UI-线程(NSThread)及其安全隐患与通信
一、基本使用
1.多线程的优缺点
//
// 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)及其安全隐患与通信的更多相关文章
- IOS UI多线程 NSThread 下载并显示图片到UIImageView
效果图 @property (weak,nonatomic)IBOutletUILabel *downLabelInfo; @property (weak,nonatomic)IBOutletUIIm ...
- iOS UI异步更新:dispatch_async 与 dispatch_get_global_queue 的使用方法
GCD (Grand Central Dispatch) 是Apple公司开发的一种技术,它旨在优化多核环境中的并发操作并取代传统多线程的编程模式. 在Mac OS X 10.6和IOS 4.0之后开 ...
- iOS-线程&&进程的深入理解
进程基本概念 进程就是一个正在运行的一个应用程序; 每一个进度都是独立的,每一个进程均在专门且手保护的内存空间内; iOS是怎么管理自己的内存的,见博客:博客地址 在Linux系统中,想要新开启一个进 ...
- iOS GCD NSOperation NSThread等多线程各种举例详解(拷贝)
2年多的iOS之路匆匆而过,期间也拜读来不少大神的博客,近来突然为自己一直做伸手党感到羞耻,是时候回馈社会.回想当年自己还是小白的时候,照着一些iOS多线程教程学,也只是照抄,只知其然.不知其所以然. ...
- iOS多线程开发--NSThread NSOperation GCD
多线程 当用户播放音频.下载资源.进行图像处理时往往希望做这些事情的时候其他操作不会被中 断或者希望这些操作过程中更加顺畅.在单线程中一个线程只能做一件事情,一件事情处理不完另一件事就不能开始,这样势 ...
- IOS任务管理之NSThread使用
前言: 无论是Android还是IOS都会使用到多任务,多任务的最小单元那就是线程,今天学习总结一下IOS的NSThread使用. NSThread使用? 第一种方式实例化 //selector :线 ...
- iOS GCD NSOperation NSThread等多线程各种举例详解
废话就不多说,直接上干货.如下图列举了很多多线程的知识点,每个按钮都写有对应的详细例子,并对运行结果进行分析,绝对拿实践结果来说话.如果各位道友发现错误之处还请指正.附上demo下载地址
- iOS:多线程NSThread的详细使用
NSThread具体使用:直接继承NSObject NSThread:. 优点:NSThread 是轻量级的,使用简单 缺点:需要自己管理线程的生命周期.线程同步.线程同步对数据的加锁会有一定的系统开 ...
- iOS开发 - 线程与进程的认识与理解
进程: 进程是指在系统中正在运行的一个应用程序,比如同时打开微信和Xcode,系统会分别启动2个进程; 每个进程之间是独立的,每个进程均运行在其专用且受保护的内存空间内; 线程: 一个进程要想执行任务 ...
随机推荐
- Andrew Ng机器学习公开课笔记 -- Generalized Linear Models
网易公开课,第4课 notes,http://cs229.stanford.edu/notes/cs229-notes1.pdf 前面介绍一个线性回归问题,符合高斯分布 一个分类问题,logstic回 ...
- php引用(&)详解及注意事项——引用返回function &a();&a()
http://www.cnblogs.com/xiaochaohuashengmi/archive/2011/09/10/2173092.html 函数的引用返回 先看代码 <?php func ...
- 如何打造高性能Web应用
Sean Hull是Heavyweight Internet Group的创始人兼高级顾问,拥有20年以上技术顾问相关经验,曾为多家知名机构提供咨询,其中包括The Hollywood Reporte ...
- Celery最佳实践(转)
原文:http://my.oschina.net/siddontang/blog/284107 英文原文:https://denibertovic.com/posts/celery-best-prac ...
- 从LayoutInflater分析XML布局解析成View的树形结构的过程
上一篇博客分析了XML布局怎么载入到Activity上.不了解的能够參考 从setContentView方法分析Android载入布局流程 上一篇博客仅仅是分析了怎么讲XML布局加入到 Activit ...
- Nginx rewrite 中break与last指令的区别
location /break/ { rewrite ^/break/(.*) /test/$1 break; return 402; } location /last/ { rewrite ^/la ...
- phpstorm psr2样式.xml
将如下内容保存为 .xml 格式 <code_scheme name="Default"> <PHPCodeStyleSettings> <optio ...
- Struct2小结:
Action小结: 实现一个Action的最常用的方式:从ActionSupport继承: DMI动态方法调用,减少配置内容: 通配符 *_* ({1},{2})的使用更方便: 接收参数的方法(一般用 ...
- 限制可编辑div只能输入纯文本
本博客转载自张鑫旭大神的一篇文章:小tip: 如何让contenteditable元素只能输入纯文本,原文地址:http://www.zhangxinxu.com/wordpress/2016/01/ ...
- WebService-WSDL简单介绍
一.什么是WSDL 网络服务描述语言(Web Services Description Language)简称WSDL.作用是通过接口之间的调用实现数据的传输.由于WSDL是基于XML格式的,所以它可 ...