标签:
- (void)viewDidLoad {
[super viewDidLoad];
/*进程:正在运行的程序 线程:进程的基本执行单元,任务执行的地方
线程的串行:1个线程中任务的执行时串行的,同一时间,1个线程只能只能执行一个任务
多线程:1个进程中可以开启多个线程,原理是CPU快速地在多条线程之间调度(切换),多了CPU吃不消
主线程/UI线程:显示/刷新/处理UI,把耗时的处理放到子线程*/
/*创建线程
手动启动线程:[thread start] 接着就会执行任务
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(text) object:nil];
自动启动线程:
[NSThread detachNewThreadSelector:@selector(text) toTarget: withObiect:]
隐式创建并启动:
[self performSelectorInBackground:@selector(text) withObject:]
获取主线程
NSThread *mainThread = [NSThread mainThread];
判断是否是主线程
BOOL *b = [mainThread isMainThread];
获取当前线程
NSThread *currentThread = [NSThread currentThread];
线程调度的优先级
+(double)threadPriority;
+(BOOL)setThreadPriority:(double)p;
设置线程的名字
-(void)setName:(NSString *)n;
-(NSString *)name;
退出线程:+exit
*/
/*线程安全:一块资源可能会被多个线程访问,容易引发数据错乱和数据安全问题
解决:线程同步技术,互斥锁 @synchronized(锁对象){//需要锁定的代码}
一个时间段只有一个线程能访问,直到该线程完事
atomic:原子属性,线性安全,为setter方法加锁
*/
/*线程间的通信:线程之间传递数据,传递任务
-(void)performSelectorOnMainThread: withObject: waitUntilDone:
-(void)performSelector: onThread: withObiect: waitUntilDone:
*/
/*线程的堵塞(调用sleep方法或者是同步锁,此时线程不可被调度):
第一种 [NSThread sleepForTimeInterval:2.0];
第二种 以当前时间为基准NSDate *date = [NSDate dateWithTimeIntervalSinceNow:4.0];
[NSThread sleepUntilDate:date];
线程的死亡:任务结束 发生异常 强制退出
创建了线程,但是线程不会立刻开启!!!!
*/
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self performSelectorInBackground:@selector(download) withObject:nil];
}
-(void)download
{ //获得一张图片
NSString *imageStrring = [NSString stringWithFormat:@"http://i6.topit.me/6/5d/45/1131907198420455d6o.jpg"];
NSURL *imageUrl = [NSURL URLWithString:imageStrring];
NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
UIImage *image = [UIImage imageWithData:imageData];
//返回主线程 第二个是要传到这个方法中的参数
[self performSelectorOnMainThread:@selector(settingImage:) withObject:image waitUntilDone:NO];
}
-(void)settingImage:(UIImage *)image
{
self.imageView.image = image;
}
//
//- (IBAction)buttonClicked:(id)sender {
// NSThread *currentThread = [NSThread currentThread];
// NSLog(@"currentThread----%@",currentThread);
// NSThread *mainThread = [NSThread mainThread];
// NSLog(@"mainThread-----%@",mainThread);
// [self creatNewThread];
//
//}
//-(void)creatNewThread
//{
// NSThread *newThread = [[NSThread alloc]initWithTarget:self selector:@selector(run) object:nil];
// newThread.name = @"线程A";
// [newThread start];
//}
//-(void)run
//{ NSThread *current = [NSThread currentThread];
// for (int i=0; i<100; i++) {
// NSLog(@"run---%@",current);
// }
//}
标签:
原文地址:http://www.cnblogs.com/haugezi/p/4856299.html