swift/IOS 多线程使用

来源:互联网 发布:下载数据恢复软件 编辑:程序博客网 时间:2024/06/05 17:18

1.swift

[objc] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //  AppDelegate.swift  
  2. //  threadDemo1  
  3. //  
  4. //  Created by 赵超 on 14-6-29.  
  5. //  Copyright (c) 2014年 赵超. All rights reserved.  
  6. //  
  7.   
  8. import UIKit  
  9.   
  10. @UIApplicationMain  
  11. class AppDelegate: UIResponder, UIApplicationDelegate {  
  12.                               
  13.     var window: UIWindow?  
  14.   
  15.     func fun1(){  
  16.         for i in 100...200{  
  17.             NSLog("%d",i)  
  18.         }  
  19.               
  20.     }  
  21.     func fun2(){  
  22.         for i in 200...300{  
  23.             NSLog("%d",i)  
  24.         }  
  25.           
  26.     }  
  27.       
  28.     func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {  
  29.         self.window = UIWindow(frame: UIScreen.mainScreen().bounds)  
  30.         // Override point for customization after application launch.  
  31.         self.window!.backgroundColor = UIColor.whiteColor()  
  32.         self.window!.makeKeyAndVisible()  
  33.           
  34.         //第一种 新建线程  
  35.         var th1=NSThread(target:self,selector:"fun1",object:nil)  
  36.         //启动线程  
  37.         th1.start()  
  38.           
  39.         //开启新线程  
  40.         NSThread.detachNewThreadSelector("fun2", toTarget:self,withObject :nil)  
  41.           
  42.           
  43.         //第三种 创建线程池  
  44.         var queue=NSOperationQueue()  
  45.         queue.maxConcurrentOperationCount=1  
  46.         queue.addOperationWithBlock({  
  47.             for i in 200...300{  
  48.                 NSLog("线程1%d",i)  
  49.             }  
  50.         })  
  51.           
  52.         var op=NSInvocationOperation(target: self,  
  53.             selector"th1",  
  54.             object: nil)  
  55.         var op1=NSInvocationOperation(target: self,  
  56.             selector"th2",  
  57.             object: nil)  
  58.         //第四种 添加线程池  
  59.         queue.addOperation(op)  
  60.         queue.addOperation(op1)  
  61.           
  62.           
  63.         //第五种 异步  
  64.         var q=dispatch_queue_create("test",nil)  
  65.         dispatch_async(q,  
  66.             {  
  67.                 for i in 0...100{  
  68.                     NSLog("异%d",i)  
  69.                 }  
  70.                 //返回主线程  
  71.                 dispatch_sync(dispatch_get_main_queue(), {  
  72.                     NSLog("是否是主线程\(NSThread.isMainThread())")  
  73.                 })  
  74.   
  75.             }  
  76.         )  
  77.           
  78.         for i in 0...100{  
  79.             NSLog("主线程%d",i)  
  80.         }  
  81.      
  82.           
  83.         return true  
  84.     }  
  85.     func th1(){  
  86.         for i in 200...300{  
  87.             NSLog("线程2%d",i)  
  88.   
  89.         }  
  90.   
  91.     }  
  92.   
  93.     func th2(){  
  94.         for i in 200...300{  
  95.             NSLog("线程3%d",i)  
  96.         }  
  97.     }  
  98.   
  99.     func applicationWillResignActive(application: UIApplication) {  
  100.         // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.  
  101.         // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.  
  102.     }  
  103.   
  104.     func applicationDidEnterBackground(application: UIApplication) {  
  105.         // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.  
  106.         // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.  
  107.     }  
  108.   
  109.     func applicationWillEnterForeground(application: UIApplication) {  
  110.         // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.  
  111.     }  
  112.   
  113.     func applicationDidBecomeActive(application: UIApplication) {  
  114.         // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.  
  115.     }  
  116.   
  117.     func applicationWillTerminate(application: UIApplication) {  
  118.         // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.  
  119.     }  
  120.   
  121.   
  122. }  


2.objective-c


[objc] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //  
  2. //  AppDelegate.m  
  3. //  ThreadDemo  
  4. //  
  5. //  Created by 赵超 on 14-8-27.  
  6. //  Copyright (c) 2014年 赵超. All rights reserved.  
  7. //  
  8.   
  9. #import "AppDelegate.h"  
  10.   
  11. @implementation AppDelegate  
  12.   
  13. -(void)action:(NSString*)test{  
  14.     NSLog(@"%@",test);  
  15.     for (int i=0; i<100;i++) {  
  16.         NSLog(@"=============action=======%d",i);  
  17.     }  
  18.       
  19. }  
  20. -(void)action2{  
  21.     for (int i=0; i<100;i++) {  
  22.         NSLog(@"=============action222222=======%d",i);  
  23.     }  
  24. }  
  25. -(void)action3{  
  26.     for (int i=0; i<100;i++) {  
  27.         NSLog(@"=============action33333=======%d",i);  
  28.     }  
  29. }  
  30. -(void)action5{  
  31.     for (int i=0; i<100;i++) {  
  32.         NSLog(@"=============action5555=======%d",i);  
  33.     }  
  34. }  
  35. -(void)action6{  
  36.     for (int i=0; i<100;i++) {  
  37.         NSLog(@"=============action6666=======%d",i);  
  38.     }  
  39.     //回到主线程  
  40.     [self performSelectorOnMainThread:@selector(mainAction) withObject:nil waitUntilDone:YES];  
  41.       
  42. }  
  43. -(void)mainAction{  
  44.     NSLog(@"++++++++%d+++++++",[NSThread isMainThread] );  
  45. }  
  46.   
  47. -(void)testThread{  
  48.     //自动  
  49.     @autoreleasepool {  
  50.        
  51.     //方法1  
  52.     NSThread *thread=[[NSThread alloc] initWithTarget:self selector:@selector(action:) object:@"test"];  
  53.     [thread start];  
  54.     //方法2  
  55.     [NSThread detachNewThreadSelector:@selector(action2) toTarget:self withObject:nil];  
  56.     //方法3  
  57.     [self performSelector:@selector(action3) withObject:nil];  
  58.     //方法4  
  59.     NSOperationQueue *perationQuere=[[NSOperationQueue alloc] init];  
  60.     [perationQuere addOperationWithBlock:^{  
  61.         for (int i=0; i<100;i++) {  
  62.             NSLog(@"=============方法444444=======%d",i);  
  63.         }  
  64.           
  65.     }];  
  66.       
  67.     //============方法5==================  
  68.     //线程队列  
  69.     NSOperationQueue *threadQuere=[[NSOperationQueue alloc] init];  
  70.     //线程并发数  
  71.     threadQuere.maxConcurrentOperationCount=1;  
  72.     //线程对象  
  73.     NSInvocationOperation *op=[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(action5) object:nil];  
  74.     NSInvocationOperation *op2=[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(action6) object:nil];  
  75.     [threadQuere addOperation:op];  
  76.     [threadQuere addOperation:op2];  
  77.       
  78.     //方法6=================GCD 多核性能高================  
  79.     dispatch_queue_t queue=dispatch_queue_create("test"NULL);  
  80.     dispatch_async(queue, ^{  
  81.         for (int i=0; i<100;i++) {  
  82.             NSLog(@"=============方法66666666666=======%d",i);  
  83.          }  
  84.     
  85.             //回到主线程  
  86.             dispatch_sync(dispatch_get_main_queue(), ^{  
  87.                 NSLog(@"++++++++%d+++++++",[NSThread isMainThread] );  
  88.             });  
  89.             NSLog(@"++++++++%d+++++++",[NSThread isMultiThreaded] );  
  90.         });  
  91.       
  92.           
  93.     }  
  94.       
  95. }  
  96.   
  97.   
  98.   
  99.   
  100. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  
  101. {  
  102.     self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];  
  103.     // Override point for customization after application launch.  
  104.     self.window.backgroundColor = [UIColor whiteColor];  
  105.     [self.window makeKeyAndVisible];  
  106.   
  107.     [self testThread];  
  108.   
  109.       
  110.     for (int i=0; i<100;i++) {  
  111.         NSLog(@"=============main=======%d",i);  
  112.     }  
  113.     return YES;  
  114. }  
  115.   
  116. - (void)applicationWillResignActive:(UIApplication *)application  
  117. {  
  118.     // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.  
  119.     // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.  
  120. }  
  121.   
  122. - (void)applicationDidEnterBackground:(UIApplication *)application  
  123. {  
  124.     // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.   
  125.     // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.  
  126. }  
  127.   
  128. - (void)applicationWillEnterForeground:(UIApplication *)application  
  129. {  
  130.     // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.  
  131. }  
  132.   
  133. - (void)applicationDidBecomeActive:(UIApplication *)application  
  134. {  
  135.     // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.  
  136. }  
  137.   
  138. - (void)applicationWillTerminate:(UIApplication *)application  
  139. {  
  140.     // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.  
  141. }  
  142.   
  143. @end  
0 0
原创粉丝点击