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个进程; 每个进程之间是独立的,每个进程均运行在其专用且受保护的内存空间内; 线程: 一个进程要想执行任务 ...
随机推荐
- Oracle AWR 之 通过dbms_workload_repository.awr_report_text(html)函数在客户端生成AWR报告
1.概述 一般情况下,awr报告都是通过在oracle服务器的sqlplus窗口调用$ORACLE_HOME/rdbms/admin/awrrpt.sql脚本生成报告.方法如下: [oracle@lo ...
- ping 10.13.5.233
3. 环境 URL选择器 tableView ping 10.13.5.233
- 以太坊geth主网全节点部署
以太坊geth主网全节点部署 #环境 ubuntu 16.4 #硬盘500GB(目前占用200G) #客户端安装 # 查看下载页面最新版 # https://ethereum.github.io/go ...
- C#基础笔记(第九天)
1.面向过程<-->面向对象面向过程:面向的是完成这件事儿的过程,强调的是完成这件事儿的动作. 面向对象:找个对象帮你做事儿.意在写出一个通用的代码,屏蔽差异. 每个人都有姓名,性别,身高 ...
- MySQL不能启动 Can't start server : Bind on unix socke
MySQL服务器突然不能启动,查看最后的启动日志如下: 080825 09:38:04 mysqld started080825 9:38:04 [ERROR] Can't start server ...
- Spark中ml和mllib的区别
转载自:https://vimsky.com/article/3403.html Spark中ml和mllib的主要区别和联系如下: ml和mllib都是Spark中的机器学习库,目前常用的机器学习功 ...
- PAT 1057 Stack [难][树状数组]
1057 Stack (30)(30 分) Stack is one of the most fundamental data structures, which is based on the pr ...
- 【PGM】Representation--Knowledge Engineering,不同的模型表示,变量的类型,structure & parameters
Part 1. 重要的区别: Template based vs. specific Directed vs. undirected Generative vs. discrimina ...
- python 2.7中文字符串的匹配(参考)
#!/bin/env python #-*- coding:utf-8 -*- import urllib import os,sys,json import ssl context = ssl._c ...
- Java基础教程:IO流与文件基础
Java:IO流与文件基础 说明: 本章内容将会持续更新,大家可以关注一下并给我提供建议,谢谢啦. 走进流 什么是流 流:从源到目的地的字节的有序序列. 在Java中,可以从其中读取一个字节序列的对象 ...