【转】IOS里的多线程编程详解

简介:

以下是开发初期收集整理的一点资料 

多线程之NSInvocationOperation
多线程编程是防止主线程堵塞,增加运行效率等等的最佳方法。而原始的多线程方法存在很多的毛病,包括线程锁死等。在Cocoa中,Apple提供了NSOperation这个类,提供了一个优秀的多线程编程方法。
本次介绍NSOperation的子集,简易方法的NSInvocationOperation:
@implementation MyCustomClass
 - (void)launchTaskWithData:(id)data
{
    //创建一个NSInvocationOperation对象,并初始化到方法
    //在这里,selector参数后的值是你想在另外一个线程中运行的方法(函数,Method)
    //在这里,object后的值是想传递给前面方法的数据
    NSInvocationOperation* theOp = [[NSInvocationOperation alloc] initWithTarget:self
                    selector:@selector(myTaskMethod:) object:data];
 
    // 下面将我们建立的操作“Operation”加入到本地程序的共享队列中(加入后方法就会立刻被执行)
    // 更多的时候是由我们自己建立“操作”队列
    [[MyAppDelegate sharedOperationQueue] addOperation:theOp];
}
 
// 这个是真正运行在另外一个线程的“方法”
- (void)myTaskMethod:(id)data
{
    // Perform the task.
}
 
@end一个NSOperationQueue 操作队列,就相当于一个线程管理器,而非一个线程。因为你可以设置这个线程管理器内可以并行运行的的线程数量等等。下面是建立并初始化一个操作队列:

@interface MyViewController : UIViewController {
 
    NSOperationQueue *operationQueue;
    //在头文件中声明该队列
}
@end
 
@implementation MyViewController
 
- (id)init 
{
    self = [super init];
    if (self) {
        operationQueue = [[NSOperationQueue alloc] init]; //初始化操作队列
        [operationQueue setMaxConcurrentOperationCount:1];
        //在这里限定了该队列只同时运行一个线程
        //这个队列已经可以使用了
    }
    return self;
}
 
- (void)dealloc
{
    [operationQueue release];
    //正如Alan经常说的,我们是程序的好公民,需要释放内存!
    [super dealloc];
}
 
@end简单介绍之后,其实可以发现这种方法是非常简单的。很多的时候我们使用多线程仅仅是为了防止主线程堵塞,而NSInvocationOperation就是最简单的多线程编程,在iPhone编程中是经常被用到的。



///////////////////////////////////////////////////////////////////////////////////////////////////
1 在主线程里加入一个loading画面……
2 {
3 [window addSubview:view_loading];
4 [NSThread detachNewThreadSelector:@selector(init_backup:) toTarget:self withObject:nil];
5 }
可以通过performSelectorOhMainThread更新UI元素,比如设置进度条等等。最后消除loading画面,载入主View。
7 - (void)init_backup:(id)sender
8 {
9 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
10 
11 // ...
12 int i = status;
13 [self performSelectorOnMainThread:@selector(show_loading:) withObject:[NSNumber numberWithInt:i] waitUntil Done:NO];
14 
15 [view_loading removeFromSuperview];
16 [window addSubview:tabcontroller_main.view];
17 [pool release];
18 }

 

///////////////////////////////////////////////////////

利用iphone的多线程实现和线程同步

从接口的定义中可以知道,NSThread和大多数iphone的接口对象一样,有两种方式可以初始化:

一种使用initWithTarget :(id)target selector:(SEL)selector object:(id)argument,但需要负责在对象的retain count为0时调用对象的release方法清理对象。

另一种则使用所谓的convenient method,这个方便接口就是detachNewThreadSelector,这个方法可以直接生成一个线程并启动它,而且无需为线程的清理负责。

#import <UIKit/UIKit.h>
@interface SellTicketsAppDelegate : NSObject <UIApplicationDelegate> {
    int tickets;
    int count;
    NSThread* ticketsThreadone;
    NSThread* ticketsThreadtwo;
    NSCondition* ticketsCondition;
    UIWindow *window;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@end

 

然后在实现中添加如下代码:
//  SellTicketsAppDelegate.m
//  SellTickets
//
//  Created by sun dfsun2009 on 09-11-10.
//  Copyright __MyCompanyName__ 2009. All rights reserved.
//
#import "SellTicketsAppDelegate.h"
@implementation SellTicketsAppDelegate
@synthesize window;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
    tickets = 100;
    count = 0;
    // 锁对象
    ticketCondition = [[NSCondition alloc] init];
    ticketsThreadone = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
    [ticketsThreadone setName:@"Thread-1"];
    [ticketsThreadone start];
    ticketsThreadtwo = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
    [ticketsThreadtwo setName:@"Thread-2"];
    [ticketsThreadtwo start];
    //[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
    // Override point for customization after application launch
    [window makeKeyAndVisible];
}
- (void)run{
    while (TRUE) {
        // 上锁
        [ticketsCondition lock];
        if(tickets > 0)
        {
            [NSThread sleepForTimeInterval:0.5];
            count = 100 - tickets;
            NSLog(@"当前票数是:%d,售出:%d,线程名:%@",tickets,count,[[NSThread currentThread] name]);
            tickets--;
        }else
        {
            break;
        }
        [ticketsCondition unlock];
    }
}
-         (void)dealloc {
    [ticketsThreadone release];
    [ticketsThreadtwo release];
    [ticketsCondition release];
    [window release];
    [super dealloc];
}
@end

-------------------------------------------------------------------------------------
// 定义
#import <UIKit/UIKit.h>

@interface ThreadSyncSampleViewController : UIViewController {
 int _threadCount;
 NSCondition *_myCondition;
}

@end

//实现文件如下:

#import "ThreadSyncSampleViewController.h"

@implementation ThreadSyncSampleViewController

 

/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

 

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
 //
 //_myCondition = nil;
 //
 _myCondition = [[NSCondition alloc] init];
 //
 NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:30 
             target:self
              selector:@selector(threadTester)
              userInfo:nil
             repeats:YES];
 [timer fire];
 
}


- (void)threadTester{
 [_myCondition lock];
 
 _threadCount = -2;
 //如果有n个要等待的thread,这里置成 -n
 [_myCondition unlock];
 //
 NSLog(@"");
 NSLog(@"------------------------------------------------------------------------------");
 [NSThread detachNewThreadSelector:@selector(threadOne) toTarget:self withObject:nil];
 [NSThread detachNewThreadSelector:@selector(threadTwo) toTarget:self withObject:nil];
 [NSThread detachNewThreadSelector:@selector(threadThree) toTarget:self withObject:nil];
 return;
}

- (void)threadOne{
 NSLog(@"@@@ In thread 111111 start.");
 [_myCondition lock];
 
 int n = rand()%5 + 1;
 NSLog(@"@@@ Thread 111111 Will sleep %d seconds ,now _threadCount is : %d",n,_threadCount);
 sleep(n);
 //[NSThread sleepForTimeInterval:n];
 _threadCount ++ ;
 NSLog(@"@@@ Thread 111111 has sleep %d seconds ,now _threadCount is : %d",n,_threadCount);
 [_myCondition signal];
 NSLog(@"@@@ Thread 1111111 has signaled ,now _threadCount is : %d",_threadCount);
 [_myCondition unlock];
 NSLog(@"@@@ In thread one complete.");
 [NSThread exit];
 return;
}

- (void)threadTwo{
 NSLog(@"### In thread 2222222 start.");
 [_myCondition lock];
 
 int n = rand()%5 + 1;
 NSLog(@"### Thread 2222222 Will sleep %d seconds ,now _threadCount is : %d",n,_threadCount);
 sleep(n);
 //   [NSThread sleepForTimeInterval:n];
 _threadCount ++ ;
 NSLog(@"### Thread 2222222 has sleep %d seconds ,now _threadCount is : %d",n,_threadCount);
 [_myCondition signal];
 NSLog(@"### Thread 2222222 has signaled ,now _threadCount is : %d",_threadCount);
 [_myCondition unlock];
 //_threadCount ++ ;
 NSLog(@"### In thread 2222222 complete.");
 [NSThread exit];
 return;
}

- (void)threadThree{
 NSLog(@"<<< In thread 333333 start.");
 [_myCondition lock];
 while (_threadCount < 0) {
  [_myCondition wait];
 }
 NSLog(@"<<< In thread 333333 ,_threadCount now is %d ,will start work.",_threadCount);
 [_myCondition unlock];
 NSLog(@"<<< In thread 333333 complete.");
 [NSThread exit];
 return;
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
 // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
 
 // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
 // Release any retained subviews of the main view.
 // e.g. self.myOutlet = nil;
}


- (void)dealloc {
 [_myCondition release];
    [super dealloc];
}

本文转自编程小翁博客园博客,原文链接:http://www.cnblogs.com/wengzilin/archive/2012/08/15/2639576.html,如需转载请自行联系原作者

相关文章
|
1月前
|
Java
如何在Java中进行多线程编程
Java多线程编程常用方式包括:继承Thread类、实现Runnable接口、Callable接口(可返回结果)及使用线程池。推荐线程池以提升性能,避免频繁创建线程。结合同步与通信机制,可有效管理并发任务。
129 6
|
4月前
|
Java API 微服务
为什么虚拟线程将改变Java并发编程?
为什么虚拟线程将改变Java并发编程?
292 83
|
23天前
|
Java 调度 数据库
Python threading模块:多线程编程的实战指南
本文深入讲解Python多线程编程,涵盖threading模块的核心用法:线程创建、生命周期、同步机制(锁、信号量、条件变量)、线程通信(队列)、守护线程与线程池应用。结合实战案例,如多线程下载器,帮助开发者提升程序并发性能,适用于I/O密集型任务处理。
185 0
|
2月前
|
算法 Java
Java多线程编程:实现线程间数据共享机制
以上就是Java中几种主要处理多线程序列化资源以及协调各自独立运行但需相互配合以完成任务threads 的技术手段与策略。正确应用上述技术将大大增强你程序稳定性与效率同时也降低bug出现率因此深刻理解每项技术背后理论至关重要.
193 16
|
6月前
|
机器学习/深度学习 消息中间件 存储
【高薪程序员必看】万字长文拆解Java并发编程!(9-2):并发工具-线程池
🌟 ​大家好,我是摘星!​ 🌟今天为大家带来的是并发编程中的强力并发工具-线程池,废话不多说让我们直接开始。
231 0
|
9月前
|
Linux
Linux编程: 在业务线程中注册和处理Linux信号
通过本文,您可以了解如何在业务线程中注册和处理Linux信号。正确处理信号可以提高程序的健壮性和稳定性。希望这些内容能帮助您更好地理解和应用Linux信号处理机制。
158 26
|
9月前
|
Linux
Linux编程: 在业务线程中注册和处理Linux信号
本文详细介绍了如何在Linux中通过在业务线程中注册和处理信号。我们讨论了信号的基本概念,并通过完整的代码示例展示了在业务线程中注册和处理信号的方法。通过正确地使用信号处理机制,可以提高程序的健壮性和响应能力。希望本文能帮助您更好地理解和应用Linux信号处理,提高开发效率和代码质量。
169 17
|
11月前
|
存储 安全 Java
Java多线程编程秘籍:各种方案一网打尽,不要错过!
Java 中实现多线程的方式主要有四种:继承 Thread 类、实现 Runnable 接口、实现 Callable 接口和使用线程池。每种方式各有优缺点,适用于不同的场景。继承 Thread 类最简单,实现 Runnable 接口更灵活,Callable 接口支持返回结果,线程池则便于管理和复用线程。实际应用中可根据需求选择合适的方式。此外,还介绍了多线程相关的常见面试问题及答案,涵盖线程概念、线程安全、线程池等知识点。
640 2
|
11月前
|
安全 算法 Java
Java多线程编程中的陷阱与最佳实践####
本文探讨了Java多线程编程中常见的陷阱,并介绍了如何通过最佳实践来避免这些问题。我们将从基础概念入手,逐步深入到具体的代码示例,帮助开发者更好地理解和应用多线程技术。无论是初学者还是有经验的开发者,都能从中获得有价值的见解和建议。 ####
|
11月前
|
安全 Java API
【JavaEE】多线程编程引入——认识Thread类
Thread类,Thread中的run方法,在编程中怎么调度多线程

热门文章

最新文章