IOS開發(100)之線程初窺

來源:互聯網
上載者:User

1 前言
本章將介紹蘋果為簡化多線程而推出的一種新方法,成為Grand Central Dispatch(簡稱GCD),它提供了一套全新的API,可以將應用程式需要執行的工作拆分成為可分散在多個線程和多個CPU上的更小的塊,從而解決了使用者體驗問題。

2 詳述
2.1 類比好使操作
接下來我們模仿一下這個耗時操作建立一個項目,當點擊Start Working的時候會等待10秒然後顯示內容,並在控制台輸出耗時:

代碼執行個體

ZYViewController.m

 

[plain] // 
//  ZYViewController.m 
//  SlowWorker 
// 
//  Created by zhangyuc on 13-6-7. 
//  Copyright (c) 2013年 zhangyuc. All rights reserved. 
// 
 
#import "ZYViewController.h" 
 
@interface ZYViewController () 
 
@end 
 
@implementation ZYViewController 
 
@synthesize startButton,resultsTextView; 
 
-(NSString *)fechSomethingFromServer{ 
    //讓線程休眠1秒 
    [NSThread sleepForTimeInterval:1]; 
    return @"Hi there"; 

 
-(NSString *)processData:(NSString *)data{ 
    [NSThread sleepForTimeInterval:2]; 
    //大寫轉換 
    return [data uppercaseString]; 

 
-(NSString *)caculateFirstResult:(NSString *)data{ 
    [NSThread sleepForTimeInterval:3]; 
    //獲得長度 
    return [NSString stringWithFormat:@"Number of chars:%d",[data length]]; 

 
-(NSString *)caculateSenondResult:(NSString *)data{ 
    [NSThread sleepForTimeInterval:4]; 
    //將“e”替換成“E” 
    return [data stringByReplacingOccurrencesOfString:@"E" withString:@"e"]; 

 
- (void)viewDidLoad 

    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 

 
- (void)didReceiveMemoryWarning 

    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 

 
- (void)dealloc { 
    [startButton release]; 
    [resultsTextView release]; 
    [super dealloc]; 

- (IBAction)doWorking:(id)sender { 
    //獲得目前時間 
    NSDate* startTime = [NSDate date]; 
    NSString* fetchedData = [self fechSomethingFromServer]; 
    NSString* processedData = [self processData:fetchedData]; 
    NSString* firstResult = [self caculateFirstResult:processedData]; 
    NSString* secondResult = [self caculateSenondResult:processedData]; 
    NSString* resultsSummary = [NSString stringWithFormat:@"First:[%@]\nSecond:[%@]",firstResult,secondResult]; 
    //為resultsTextView的text屬性賦值 
    resultsTextView.text = resultsSummary; 
    NSDate* endTime = [NSDate date]; 
    //獲得時間差單位 s 
    NSLog(@"Completed in %f seconds",[endTime timeIntervalSinceDate:startTime]); 

@end 

//
//  ZYViewController.m
//  SlowWorker
//
//  Created by zhangyuc on 13-6-7.
//  Copyright (c) 2013年 zhangyuc. All rights reserved.
//

#import "ZYViewController.h"

@interface ZYViewController ()

@end

@implementation ZYViewController

@synthesize startButton,resultsTextView;

-(NSString *)fechSomethingFromServer{
    //讓線程休眠1秒
    [NSThread sleepForTimeInterval:1];
    return @"Hi there";
}

-(NSString *)processData:(NSString *)data{
    [NSThread sleepForTimeInterval:2];
    //大寫轉換
    return [data uppercaseString];
}

-(NSString *)caculateFirstResult:(NSString *)data{
    [NSThread sleepForTimeInterval:3];
    //獲得長度
    return [NSString stringWithFormat:@"Number of chars:%d",[data length]];
}

-(NSString *)caculateSenondResult:(NSString *)data{
    [NSThread sleepForTimeInterval:4];
    //將“e”替換成“E”
    return [data stringByReplacingOccurrencesOfString:@"E" withString:@"e"];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
 // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [startButton release];
    [resultsTextView release];
    [super dealloc];
}
- (IBAction)doWorking:(id)sender {
    //獲得目前時間
    NSDate* startTime = [NSDate date];
    NSString* fetchedData = [self fechSomethingFromServer];
    NSString* processedData = [self processData:fetchedData];
    NSString* firstResult = [self caculateFirstResult:processedData];
    NSString* secondResult = [self caculateSenondResult:processedData];
    NSString* resultsSummary = [NSString stringWithFormat:@"First:[%@]\nSecond:[%@]",firstResult,secondResult];
    //為resultsTextView的text屬性賦值
    resultsTextView.text = resultsSummary;
    NSDate* endTime = [NSDate date];
    //獲得時間差單位 s
    NSLog(@"Completed in %f seconds",[endTime timeIntervalSinceDate:startTime]);
}
@end
運行結果:

初始化:

 
 


當點擊Start Working後等待大約10秒鐘:

 
 


控制台運行結果:


2013-06-07 11:18:08.360 SlowWorker[868:c07] Completed in 10.005586 seconds

 


2.2 線程基礎知識
大部分現代作業系統都支援線程的概念。每個進程可以包含多個線程,他們全部同時進行。一個進程中的所有線程共用的可執行程式代碼和相同的全域資料。每個線程也可以擁有一些專屬的資料。線程可以使用一種稱為互斥或者鎖的特殊結構,這種結構可以確保特定的代碼塊無法一次被多個線程運行。有助於保證正確的結果。

再出理線程的時候,常見問題就是安全執行緒。舉例來說在Cocoa Touch中,Foundation架構通常被視為是安全執行緒的,而UIKit架構在很大程度上被視為不安全的。在運行IOS應用程式中,處理任何的UIKit對象的所有方法調用都應從系統的線程內執行,該線程通常成為主線程。預設情況下,主線程執行IOS應用程式的所有操作(比如處理由使用者觸發的操作)。

2.3 工作單元
對於多線程操作蘋果公司推薦使用的解決方案:將長期啟動並執行任務拆分成多個工作單元,並將這些單元添加到執行隊列中。系統會為我們管理這些隊列,為我們在多個線程上執行工作單元。我們不需要直接啟動和管理後台線程,可以從通常實現並發應用程式所涉及的太多“登記“工作中脫離出來,系統會為我們完成這些工作。

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.