- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease]; //建立線程的第一種方式 NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"universe"]; [thread start]; [thread release]; //建立線程的第二種方式,NSThread類方法 [NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"yuzhou"]; //建立線程的第三種方法 NSObject方法 [self performSelectorInBackground:@selector(run:) withObject:@"nsobject thread"]; //建立線程的第四種方式 NSOperationQueue *oprationQueue = [[NSOperationQueue alloc] init]; [oprationQueue addOperationWithBlock:^{ //這個block語句塊在子線程中執行 NSLog(@"oprationQueue"); }]; [oprationQueue release]; //第五種建立線程的方式 NSOperationQueue *oprationQueue1 = [[NSOperationQueue alloc] init]; oprationQueue1.maxConcurrentOperationCount = 1;//指定池子的併發數 //NSOperation 至關於java中的runnable接口,繼承自它的就至關一個任務 NSInvocationOperation *invation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run:) object:@"invation"]; [oprationQueue1 addOperation:invation];//將任務添加到池子裏面,能夠給池子添加多個任務,而且指定它的併發數 [invation release]; //第二個任務 NSInvocationOperation *invation2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run2:) object:@"invocation2"]; invation2.queuePriority = NSOperationQueuePriorityHigh;//設置線程優先級 [oprationQueue1 addOperation:invation2]; [invation2 release]; [oprationQueue1 release]; //調用主線程,用來子線程和主線程交互,最後面的那個boolean參數,若是爲yes就是等這個方法執行完了在執行後面的代碼;若是爲no的話,就是無論這個方法執行完了沒有,接着往下走 [self performSelectorOnMainThread:@selector(onMain) withObject:self waitUntilDone:YES]; //---------------------GCD----------------------支持多核,高效率的多線程技術 //建立多線程第六種方式 dispatch_queue_t queue = dispatch_queue_create("name", NULL); //建立一個子線程 dispatch_async(queue, ^{ // 子線程code... .. NSLog(@"GCD多線程"); //回到主線程 dispatch_sync(dispatch_get_main_queue(), ^{//其實這個也是在子線程中執行的,只是把它放到了主線程的隊列中 Boolean isMain = [NSThread isMainThread]; if (isMain) { NSLog(@"GCD主線程"); } }); }); self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; return YES; } - (void)onMain { Boolean b = [NSThread isMainThread]; if (b) { NSLog(@"onMain;;%d",b); } } - (void) run:(NSString*)str { NSLog(@"多線程運行:::%@",str); } - (void) run2:(NSString*)str { NSLog(@"多線程運行:::%@",str); }