IOS多線程開發之NSThread

來源:互聯網
上載者:User

標籤:

概要        使用NSThread的例子,線程建立、啟動、線程同步、鎖、線程的互動,需要注意的時線程的互動,因為IOS規定只有主線程能夠修改UI,所以如果子線程要修改UI的話,需要與主線程互動,即調用方法- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;實現
範例程式碼
////  ViewController.m//  NSThreadDemo////  Created by wangwei on 14/12/31.//  Copyright (c) 2014年 arbboter. All rights reserved.//#import "ViewController.h"@interface ViewController (){    NSMutableArray* sellTicketThread;    NSCondition* sellTicketCondition;    NSInteger numberOfSellThread;    NSInteger nunberOfTickets;}@end@implementation ViewController- (void)viewDidLoad{    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.        sellTicketThread = [[NSMutableArray alloc] init];        numberOfSellThread = 3;    nunberOfTickets = 24;        /** create thread */    NSThread* sellTicket = nil;    for (NSInteger i=0; i<numberOfSellThread; i++)    {        sellTicket = [[NSThread alloc] initWithTarget:self selector:@selector(sellTicket) object:nil];        sellTicket.name = [NSString stringWithFormat:@"Ticket Windows %ld", i];        [sellTicketThread addObject:sellTicket];    }        /** create thread condition */    sellTicketCondition = [[NSCondition alloc] init];        /** start all thread */    for (NSThread* t in sellTicketThread)    {        [t start];    }        self.messageTicket.frame = CGRectMake(0, 20, 330, 600);    self.messageTicket.text = @"Welcome to 12306.\n";    self.messageTicket.textColor = [UIColor blackColor];    self.messageTicket.editable = NO;}- (void) sellTicket{    NSString* message = nil;    BOOL bRun = YES;        while (bRun)    {        [sellTicketCondition lock];                if (nunberOfTickets>0)        {            nunberOfTickets--;            message = [NSString stringWithFormat:@"[%@] get ticket %02ld. [%02ld Left]\n",                       [[NSThread currentThread] name], nunberOfTickets+1, nunberOfTickets];        }        else        {            message = [NSString stringWithFormat:@"[%@] Sorry, but we have no ticket lefy.\n", [[NSThread currentThread] name]];            bRun = NO;        }                /** 子線程不能修改APP的UI的, 所以需要主線程修改 */        [self performSelectorOnMainThread:@selector(addMessageToView:) withObject:message waitUntilDone:YES];        [sellTicketCondition unlock];                /** wait for a moment */        sleep(arc4random()%5+1);    }}/** 互動資訊 */- (void)addMessageToView:(NSString*)message{    self.messageTicket.text = [self.messageTicket.text stringByAppendingString:message];}- (void)didReceiveMemoryWarning{    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end

結果展示
主要方法列表
 //返回當前線程+ (NSThread *)currentThread;          // 通過類方法建立一個線程+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)argument;// 判斷是否為多線程+ (BOOL)isMultiThreaded;- (NSMutableDictionary *)threadDictionary;+ (void)sleepUntilDate:(NSDate *)date;+ (void)sleepForTimeInterval:(NSTimeInterval)ti;//  退出線程+ (void)exit;// 線程屬性值+ (double)threadPriority ;+ (BOOL)setThreadPriority:(double)p ;// 線程函數地址+ (NSArray *)callStackReturnAddresses;// 設定與返回線程名稱- (void)setName:(NSString *)n;- (NSString *)name;// 線程堆棧- (NSUInteger)stackSize;- (void)setStackSize:(NSUInteger)s;// 判斷當前線程是否為主線程- (BOOL)isMainThread;+ (BOOL)isMainThread;+ (NSThread *)mainThread;// 線程對象初始化操作   (通過建立線程對象 ,需要 手工指定線程函數與各種屬性)- (id)init;// 線上程對象初始化時建立一個線程(指定線程函數)- (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument;// 是否在執行- (BOOL)isExecuting;// 是否已經結束 - (BOOL)isFinished;// 是否取消的- (BOOL)isCancelled;// 取消操作- (void)cancel;// 在主線程上執行aSelector所對應的代碼,因為有些代碼只能在主線程上執行,比如修改UI- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;// 線程啟動- (void)start;- (void)main;    // thread body method


IOS多線程開發之NSThread

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.