欢迎访问移动开发之家(rcyd.net),关注移动开发教程。移动开发之家  移动开发问答|  每日更新
页面位置 : > > > 内容正文

iOS-多线程(模拟火车票售票系统)

来源: 开发者 投稿于  被查看 29856 次 评论:25

iOS-多线程(模拟火车票售票系统)


 

一、实现结果

在本程序中,用到7个控件,三个说明性label,三个输出口label,一个button。

\

二、代码的属性部分

用到的属性:3个输出label,一个按钮

一个按钮方法

 

#import

 

@interface WeSecondThreadViewController : UIViewController

{ //剩余票数和售出票数

int _leftTicks;

int _saledTicks;

//两个线程

NSThread *_firstThread;

NSThread *_secondThread;

//lock条件

NSCondition *_ticksConfition;

}

@property (retain, nonatomic) IBOutlet UILabel *leftTicksLabel;

@property (retain, nonatomic) IBOutlet UILabel *saledTicksLabel;

@property (retain, nonatomic) IBOutlet UILabel *currentThreadLabel;

@property (retain, nonatomic) IBOutlet UIButton *startBtn;

- (IBAction)startAction:(id)sender;

 

@end

三、方法实现部分

//剩余票数和售出票数初始化

- (void)viewDidLoad

{

[super viewDidLoad];

_leftTicks = 100;

_saledTicks = 0;

_ticksConfition = [[NSCondition alloc]init];

// Do any additional setup after loading the view from its nib.

}

//按钮的响应方法

- (IBAction)startAction:(id)sender

{

//线程一开始

_firstThread = [[NSThread alloc]initWithTarget:self selector:@selector(startThread:) object:nil];

[_firstThread setName:@Thread_1];

[_firstThread start];

//线程二开始

_secondThread = [[NSThread alloc]initWithTarget:self selector:@selector(startThread:) object:nil];

[_secondThread setName:@Thread_2];

[_secondThread start];

}

- (void)startThread:(id)sender

{

while (TRUE)

{

//线程锁,使一二线程交互

[_ticksConfition lock];

if (_leftTicks > 0 )

{

[NSThread sleepForTimeInterval:0.1];

_leftTicks --;

_saledTicks = 100 - _leftTicks;

NSString *pstr = [[NSThread currentThread]name];

NSLog(@售出票数:%i 剩余票数%i 当前线程%@,_saledTicks,_leftTicks,pstr);

}

else if (_leftTicks == 0)

{

NSLog(@票已售完);

break;

}

//在主线程中更新

[self performSelectorOnMainThread:@selector(updateMyView:) withObject:[[NSThread currentThread]name] waitUntilDone:YES];

//解锁

[_ticksConfition unlock];

}

}

//屏幕上更新

- (void)updateMyView:(id)sender

{

self.leftTicksLabel.text = [NSString stringWithFormat:@%i,_leftTicks];

self.saledTicksLabel.text = [NSString stringWithFormat:@%i,_saledTicks];

self.currentThreadLabel.text = (NSString*)sender;

 

if (_leftTicks == 0)

{

UIAlertView *pAlter = [[UIAlertView alloc]initWithTitle:@通知 message:@今日票已售完 delegate:nil cancelButtonTitle:nil otherButtonTitles:@确认, nil];

[pAlter show];

[pAlter release];

}

 

}

相关demo下载地址:http://download.csdn.net/detail/u012887301/6777319

用户评论