注册 登录  
 加关注
查看详情
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

云水禅心

淡若秋菊何妨瘦, 清到梅花不畏寒.

 
 
 

日志

 
 

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

2011-09-02 10:55:10|  分类: iphone |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
从接口的定义中可以知道,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];

}


@end


  评论这张
 
阅读(854)| 评论(1)
推荐 转载

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2018