天天看點

iOS-多線程(模拟火車票售票系統)

關于線程的介紹見上一片博文,iOS單線程:http://blog.csdn.net/yakerwei/article/details/17589709

一、實作結果

在本程式中,用到7個控件,三個說明性label,三個輸出口label,一個button。

iOS-多線程(模拟火車票售票系統)

二、代碼的屬性部分

用到的屬性:3個輸出label,一個按鈕

一個按鈕方法

#import <UIKit/UIKit.h>

@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