swift/IOS 多线程使用

1.swift

//  AppDelegate.swift
//  threadDemo1
//
//  Created by 赵超 on 14-6-29.
//  Copyright (c) 2014年 赵超. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
                            
    var window: UIWindow?

    func fun1(){
        for i in 100...200{
            NSLog("%d",i)
        }
            
    }
    func fun2(){
        for i in 200...300{
            NSLog("%d",i)
        }
        
    }
    
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
        // Override point for customization after application launch.
        self.window!.backgroundColor = UIColor.whiteColor()
        self.window!.makeKeyAndVisible()
        
        //第一种 新建线程
        var th1=NSThread(target:self,selector:"fun1",object:nil)
        //启动线程
        th1.start()
        
        //开启新线程
        NSThread.detachNewThreadSelector("fun2", toTarget:self,withObject :nil)
        
        
        //第三种 创建线程池
        var queue=NSOperationQueue()
        queue.maxConcurrentOperationCount=1
        queue.addOperationWithBlock({
            for i in 200...300{
                NSLog("线程1%d",i)
            }
        })
        
        var op=NSInvocationOperation(target: self,
            selector: "th1",
            object: nil)
        var op1=NSInvocationOperation(target: self,
            selector: "th2",
            object: nil)
        //第四种 添加线程池
        queue.addOperation(op)
        queue.addOperation(op1)
        
        
        //第五种 异步
        var q=dispatch_queue_create("test",nil)
        dispatch_async(q,
            {
                for i in 0...100{
                    NSLog("异%d",i)
                }
                //返回主线程
                dispatch_sync(dispatch_get_main_queue(), {
                    NSLog("是否是主线程\(NSThread.isMainThread())")
                })

            }
        )
        
        for i in 0...100{
            NSLog("主线程%d",i)
        }
   
        
        return true
    }
    func th1(){
        for i in 200...300{
            NSLog("线程2%d",i)

        }

    }

    func th2(){
        for i in 200...300{
            NSLog("线程3%d",i)
        }
    }

    func applicationWillResignActive(application: UIApplication) {
        // 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.
        // 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.
    }

    func applicationDidEnterBackground(application: UIApplication) {
        // 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.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(application: UIApplication) {
        // 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.
    }

    func applicationDidBecomeActive(application: UIApplication) {
        // 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.
    }

    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


}


2.objective-c


//
//  AppDelegate.m
//  ThreadDemo
//
//  Created by 赵超 on 14-8-27.
//  Copyright (c) 2014年 赵超. All rights reserved.
//

#import "AppDelegate.h"

@implementation AppDelegate

-(void)action:(NSString*)test{
    NSLog(@"%@",test);
    for (int i=0; i<100;i++) {
        NSLog(@"=============action=======%d",i);
    }
    
}
-(void)action2{
    for (int i=0; i<100;i++) {
        NSLog(@"=============action222222=======%d",i);
    }
}
-(void)action3{
    for (int i=0; i<100;i++) {
        NSLog(@"=============action33333=======%d",i);
    }
}
-(void)action5{
    for (int i=0; i<100;i++) {
        NSLog(@"=============action5555=======%d",i);
    }
}
-(void)action6{
    for (int i=0; i<100;i++) {
        NSLog(@"=============action6666=======%d",i);
    }
    //回到主线程
    [self performSelectorOnMainThread:@selector(mainAction) withObject:nil waitUntilDone:YES];
    
}
-(void)mainAction{
    NSLog(@"++++++++%d+++++++",[NSThread isMainThread] );
}

-(void)testThread{
    //自动
    @autoreleasepool {
     
    //方法1
    NSThread *thread=[[NSThread alloc] initWithTarget:self selector:@selector(action:) object:@"test"];
    [thread start];
    //方法2
    [NSThread detachNewThreadSelector:@selector(action2) toTarget:self withObject:nil];
    //方法3
    [self performSelector:@selector(action3) withObject:nil];
    //方法4
    NSOperationQueue *perationQuere=[[NSOperationQueue alloc] init];
    [perationQuere addOperationWithBlock:^{
        for (int i=0; i<100;i++) {
            NSLog(@"=============方法444444=======%d",i);
        }
        
    }];
    
    //============方法5==================
    //线程队列
    NSOperationQueue *threadQuere=[[NSOperationQueue alloc] init];
    //线程并发数
    threadQuere.maxConcurrentOperationCount=1;
    //线程对象
    NSInvocationOperation *op=[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(action5) object:nil];
    NSInvocationOperation *op2=[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(action6) object:nil];
    [threadQuere addOperation:op];
    [threadQuere addOperation:op2];
    
    //方法6=================GCD 多核性能高================
    dispatch_queue_t queue=dispatch_queue_create("test", NULL);
    dispatch_async(queue, ^{
        for (int i=0; i<100;i++) {
            NSLog(@"=============方法66666666666=======%d",i);
         }
  
            //回到主线程
            dispatch_sync(dispatch_get_main_queue(), ^{
                NSLog(@"++++++++%d+++++++",[NSThread isMainThread] );
            });
            NSLog(@"++++++++%d+++++++",[NSThread isMultiThreaded] );
        });
    
        
    }
    
}




- (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];

    [self testThread];

    
    for (int i=0; i<100;i++) {
        NSLog(@"=============main=======%d",i);
    }
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // 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.
    // 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.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // 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. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // 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.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // 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.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end


转载于:https://www.cnblogs.com/whzhaochao/p/5023439.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值