NS类 - NSThread几种创建方法
(2013-05-13 11:25:08)
标签:
nsthreadit |
分类: Mac/IOS那些事 |
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window
= [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]
autorelease];
// Override
point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
[self.window
makeKeyAndVisible];
//第一种多线程的方法, 直接来创建
NSThread
*thread = [[NSThread alloc]initWithTarget:self
selector:@selector(mutableThread:) object:@"mutable"];
[thread
start];
for(int
i=0;i<100;i++)
{
NSLog(@"maint--:%d",i);
}
//第二种 直接调用nsthread的类方法
[NSThread
detachNewThreadSelector:@selector(mutableThread:) toTarget:self
withObject:nil];
// 第三种
[self
performSelectorInBackground:@selector(mutableThread:)
withObject:nil];
//第四种 直接添加一个block再子线程上 这样不用单独写方法 其实这个是创建了一个线程池 叫线程队列
//可以添加多个
NSOperationQueue *threadQueue =
[[NSOperationQueue alloc]init];
threadQueue
addOperationWithBlock:^{
for(int i=0;i<100;i++)
{
NSLog(@"thread --:%d",i);
}
}
//第五种在 operationQueue队列中添加多个线程 ui的操作都是在主线程的
NSOperationQueue *operationQueue = [[NSOperationQueue
alloc]init];
//设置最大的线程数
operationQueue.maxConcurrentOperationCount = 2;
NSInvocationOperation *invocationOperation =
[[NSInvocationOperation alloc]initWithTarget:self
selector:@selector(mutableThread:) object:nil];
NSInvocationOperation *invocationOperation2 =
[[NSInvocationOperation alloc]initWithTarget:self
selector:@selector(mutableThread2:) object:nil];
//设置优先级
invocationOperation2.queuePriority =
NSOperationQueuePriorityHigh;
[operationQueue addOperation:invocationOperation];
[operationQueue addOperation:invocationOperation2];
//回到主线程 因为ui不能在子线程执行
[self
performSelectorOnMainThread:@selector(backToMain) withObject:nil
waitUntilDone:YES];
//第六种使用GCD
dispatch_queue_t GCDQueue =
dispatch_queue_create("GCDTest", nil);
dispatch_async(GCDQueue, ^{
for(int i=0;i<100;i++)
{
NSLog(@"GCDthread --:%d",i);
}
BOOL isMulti = [NSThread isMultiThreaded];
if(isMulti){
NSLog(@"isMutalThread!");
}
dispatch_sync(dispatch_get_main_queue(), ^{
BOOL isMain = [NSThread isMainThread];
if (isMain) {
NSLog(@"backToMainThread ..");
{
//第一种多线程的方法, 直接来创建
//第二种 直接调用nsthread的类方法
// 第三种
//第四种 直接添加一个block再子线程上 这样不用单独写方法 其实这个是创建了一个线程池 叫线程队列
//可以添加多个
//第五种在 operationQueue队列中添加多个线程 ui的操作都是在主线程的
//回到主线程 因为ui不能在子线程执行
//第六种使用GCD