AppDelegate.m
//
// AppDelegate.m
// UI12-task-01
//
// Created by keyzhang on 14-7-21.
// Copyright (c) 2014年 keyzhang. All rights reserved.
//
#import "AppDelegate.h"
#import "Person.h"
@implementation AppDelegate
{
UIImageView *_imgView;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
_imgView = [[UIImageView alloc] initWithFrame:self.window.bounds];
_imgView.backgroundColor = [UIColor grayColor];
[self.window addSubview:_imgView];
//第一种方法创建线程
// NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
// [thread start];//手动开启线程
//第二种方法
// [NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
//第三种方法
// [self performSelectorInBackground:@selector(run) withObject:nil];
//第四种方式
//初始化一个操作队列或者线程池
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//设置同时运行的线程数
[queue setMaxConcurrentOperationCount:2];
//往线程池里添加一个操作
// [queue addOperationWithBlock:^{
// NSLog(@"block:%d",[[NSThread currentThread] isMainThread]);
// [self run];
// }];
//第五种方法
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run) object:nil];
[operation setQueuePriority:NSOperationQueuePriorityNormal];
[queue addOperation:operation];
// //第六种方法
// Person *ps = [[Person alloc] init];
// //设置作业在队列当中的优先级
// [ps setQueuePriority:NSOperationQueuePriorityVeryLow];
// [queue addOperation:ps];
for (int i = 0; i<10; i++) {
NSLog(@"-----------主线程%d-------------",i);
}
return YES;
}
- (void)run
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
for (int i = 0; i<10; i++) {
NSLog(@"-----------run线程%d-------------",i);
}
NSURL *url = [NSURL URLWithString:@"http://g.hiphotos.baidu.com/image/pic/item/a8ec8a13632762d00905bd2da2ec08fa513dc66d.jpg"];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
//UI操作必须放在主线程中执行
[self performSelectorOnMainThread:@selector(showImage:) withObject:image waitUntilDone:NO];
NSLog(@"finish");
//通过这种方式创建的定时器是默认已经添加到runloop里面
// [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeAction) userInfo:nil repeats:YES];
NSTimer *timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timeAction) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] run];
[pool release];
}
- (void)showImage:(UIImage *)img
{
_imgView.image = img;
}
- (void)timeAction
{
NSLog(@"timeAction");
}
@end
Person继承于NSOperation
Person.m
//线程的入口函数,执行具体的操作
- (void)main
{
NSLog(@"person:%d",[[NSThread currentThread] isMainThread]);
for (int i = 0; i<10; i++) {
NSLog(@"--------person线程%d------",i);
}
}