iOS 多线程NSThread 三
来源:互联网 发布:上饶师范学校教务网络 编辑:程序博客网 时间:2024/05/21 20:22
基本概念
- 简介
- 语言:OC
- 线程生命周期:程序员管理
- 使用频率:偶尔使用
- 更加面向对象
- 简单易用,可直接操作线程对象
创建和启动线程
- 一个NSThread对象就代表一条线程
- 创建、启动线程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];[thread start];// 线程一启动,就会在线程thread中执行self的run方法
- 主线程相关用法
+ (NSThread *)mainThread; // 获得主线程- (BOOL)isMainThread; // 是否为主线程+ (BOOL)isMainThread; // 是否为主线程
其他用法
- 获得当前线程
NSThread *current = [NSThread currentThread];
- 线程的名字
- (void)setName:(NSString *)n;- (NSString *)name;
其他创建线程方式
下面2种创建线程方式的缺点
:简单快捷优点
:无法对线程进行更详细的设置
- 创建线程后自动启动线程
[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
- 隐式创建并启动线程
[self performSelectorInBackground:@selector(run) withObject:nil];
线程的状态
控制线程状态
- 启动线程
- (void)start;// 进入就绪状态 -> 运行状态。当线程任务执行完毕,自动进入死亡状态
- 阻塞(暂停)线程
+ (void)sleepUntilDate:(NSDate *)date;+ (void)sleepForTimeInterval:(NSTimeInterval)ti;// 进入阻塞状态
- 强制停止线程
+ (void)exit;// 进入死亡状态// 注意:一旦线程停止(死亡)了,就不能再次开启任务
经典案例一:卖票
#import "ViewController.h"@interface ViewController ()/** 票的总数 */@property (nonatomic, assign) NSInteger ticketCount;/** 售票员1 */@property (nonatomic, strong) NSThread *thread1;/** 售票员2 */@property (nonatomic, strong) NSThread *thread2;/** 售票员3 */@property (nonatomic, strong) NSThread *thread3;@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; self.ticketCount = 100; // 开启三条线程 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"; self.thread3 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil]; self.thread3.name = @"售票员3";}- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [self.thread1 start]; [self.thread2 start]; [self.thread3 start];}- (void)saleTicket{ while (1) { @synchronized(self) { // 必需要加锁,保证线程安全 // 先取出总数 NSInteger count = self.ticketCount; if (count > 0) { self.ticketCount = count - 1; NSLog(@"%@卖了一张票,还剩下%zd张", [NSThread currentThread].name, self.ticketCount); } else { NSLog(@"票已经卖完了"); break; } } }}@end
注意:必须要用@synchronized加锁,如果未加锁会导致线程不安全,如下图剩余张数可看出
1 0
- iOS 多线程NSThread 三
- iOS-多线程编程学习之NSThread(三)
- 多线程之三:NSThread
- iOS 多线程 NSThread
- IOS 多线程 NSThread
- iOS多线程 nsthread
- ios NSThread多线程
- iOS多线程开发 NSThread
- IOS 多线程 线程NSThread
- iOS多线程之NSThread
- iOS多线程开发 NSThread
- ios多线程之NSThread
- IOS 多线程 线程NSThread
- iOS多线程之NSThread
- iOS多线程之NSThread
- iOS 多线程NSThread
- IOS 多线程(2) --NSThread
- iOS多线程学习---NSThread
- hdu 1937 Finding Seats 尺取法
- dp-Supporting Different Screens
- 快速排序模版
- makefile详解
- dxp中的一批元件的锁定与解除
- iOS 多线程NSThread 三
- Android API Guides 阅读笔记(3)----Intent and Intent Filter
- 在java项目开发中要加入的spring的jar包(以spring 3.1版本为例)
- centos最小化安装后再安装图形界面
- 杭电1018 Big Number
- java IO图
- Nodejs进程管理模块forever详解
- zoj2417 Lowest Bit
- asp.net重写服务器控件