iOS-多线程 ,整理集锦,多种线程的创建
生活随笔
收集整理的這篇文章主要介紹了
iOS-多线程 ,整理集锦,多种线程的创建
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
2 {
3 self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
4
5 //創建線程的第一種方式
6 NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"universe"];
7 [thread start];
8 [thread release];
9
10
11 //創建線程的第二種方式,NSThread類方法
12 [NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"yuzhou"];
13
14
15 //創建線程的第三種方法 NSObject方法
16 [self performSelectorInBackground:@selector(run:) withObject:@"nsobject thread"];
17
18 //創建線程的第四種方式
19 NSOperationQueue *oprationQueue = [[NSOperationQueue alloc] init];
20 [oprationQueue addOperationWithBlock:^{
21 //這個block語句塊在子線程中執行
22 NSLog(@"oprationQueue");
23 }];
24 [oprationQueue release];
25
26 //第五種創建線程的方式
27 NSOperationQueue *oprationQueue1 = [[NSOperationQueue alloc] init];
28 oprationQueue1.maxConcurrentOperationCount = 1;//指定池子的并發數
29
30 //NSOperation 相當于java中的runnable接口,繼承自它的就相當一個任務
31 NSInvocationOperation *invation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run:) object:@"invation"];
32 [oprationQueue1 addOperation:invation];//將任務添加到池子里面,可以給池子添加多個任務,并且指定它的并發數
33 [invation release];
34
35 //第二個任務
36 NSInvocationOperation *invation2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run2:) object:@"invocation2"];
37 invation2.queuePriority = NSOperationQueuePriorityHigh;//設置線程優先級
38 [oprationQueue1 addOperation:invation2];
39 [invation2 release];
40
41 [oprationQueue1 release];
42
43 //調用主線程,用來子線程和主線程交互,最后面的那個boolean參數,如果為yes就是等這個方法執行完了在執行后面的代碼;如果為no的話,就是不管這個方法執行完了沒有,接著往下走
44 [self performSelectorOnMainThread:@selector(onMain) withObject:self waitUntilDone:YES];
45
46 //---------------------GCD----------------------支持多核,高效率的多線程技術
47 //創建多線程第六種方式
48 dispatch_queue_t queue = dispatch_queue_create("name", NULL);
49 //創建一個子線程
50 dispatch_async(queue, ^{
51 // 子線程code... ..
52 NSLog(@"GCD多線程");
53
54 //回到主線程
55 dispatch_sync(dispatch_get_main_queue(), ^{//其實這個也是在子線程中執行的,只是把它放到了主線程的隊列中
56 Boolean isMain = [NSThread isMainThread];
57 if (isMain) {
58 NSLog(@"GCD主線程");
59 }
60 });
61 });
62
63
64 self.window.backgroundColor = [UIColor whiteColor];
65 [self.window makeKeyAndVisible];
66 return YES;
67 }
68
69 - (void)onMain
70 {
71 Boolean b = [NSThread isMainThread];
72 if (b) {
73 NSLog(@"onMain;;%d",b);
74 }
75 }
76
77 - (void) run:(NSString*)str
78 {
79 NSLog(@"多線程運行:::%@",str);
80 }
81
82 - (void) run2:(NSString*)str
83 {
84 NSLog(@"多線程運行:::%@",str);
85 }
86 這些都是基本的線程創建,用NSThread來進行創建線程比較簡單,如果是單一的創建線程可以用NSThread。直接創建可以使用。只需把線程執行的函數和方法寫入即可創建一個線程出來。。
87 View Code
?
轉載于:https://www.cnblogs.com/Wild-orangutans/p/3824366.html
總結
以上是生活随笔為你收集整理的iOS-多线程 ,整理集锦,多种线程的创建的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CentOS 6.4利用xampp安装b
- 下一篇: Git帮助文档阅读笔记----第二章