现在的位置: 首页 > 综合 > 正文

IOS多线程Thread实现简单的售票系统

2014年03月15日 ⁄ 综合 ⁄ 共 5567字 ⁄ 字号 评论关闭

火车票售票系统大家已经非常熟悉了,但是自己做一个简单的售票系统,不知道大家有没有兴趣呢,当然了我们只需要考虑车票是否有剩余,卖出去了多少票,卖完后就不能再卖了,利用我们学过的线程的知识,利用多线程来实现它,首先呢,我们新建一个空白的工程,然后再HHLAppDelegate.m文件里面新建一个新建一个tabbarControl ,视图控制区的对象,把这个视图控制器对象添加为tabBarControl的Item,接下来我们需要做的就是通过拖拽控件的方式,新建如下图所示:

具体的代码如下:

HHLAppDelegate.h

#import <UIKit/UIKit.h>



@interface HHLAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@end

HHLAppDelegate.m

#import "HHLAppDelegate.h"


#import "HHLViewController2.h"
#import "tableViewController.h"

@implementation HHLAppDelegate

- (void)dealloc
{
    [_window release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    
   //HHLViewController *viewController = [[HHLViewController alloc]initWithNibName:@"HHLViewController" bundle:nil];
    HHLViewController2 *viewController2 = [[HHLViewController2 alloc]initWithNibName:nil bundle:nil];
    
    //tableViewController *tableView = [[tableViewController alloc]initWithNibName:nil bundle:nil];
    
    UITabBarController *pTabbarVC = [[UITabBarController alloc]init];
    pTabbarVC.viewControllers = [NSArray arrayWithObjects:viewController2, nil];
    self.window.rootViewController = pTabbarVC;
    //[tableView release];
    [pTabbarVC release];
    [viewController2 release];
    //[viewController release];
    
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end

HHLViewController2.h

#import <UIKit/UIKit.h>

@interface HHLViewController2 : UIViewController
{
    int _saleTickets;
    int _leftTickets;
    NSThread *_firstThread;
    NSThread *_secondThread;
    NSCondition *_ticketsCondition;
 
}

@property (retain,nonatomic) IBOutlet UILabel *labelLeftTickets;
@property (retain,nonatomic) IBOutlet UILabel *labelSaleTickets;
@property (retain,nonatomic) IBOutlet UILabel *labelCurrentThread;
//@property (retain,nonatomic) UIButton *pBtn;
//-(void)btnPressed:(id)sender;
 @end

HHLViewController2.m

#import "HHLViewController2.h"

@interface HHLViewController2 ()

@end

@implementation HHLViewController2

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.tabBarItem.title =@"ThreadTwo";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
  // self.pBtn
    
    _leftTickets = 100;
    _saleTickets = 10;
    _ticketsCondition =[[NSCondition alloc]init];
    
    UIButton *pBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    pBtn.frame = CGRectMake(100, 360, 80, 40);
    [pBtn setTitle:@"Start" forState:UIControlStateNormal];
    [pBtn addTarget:self action:@selector(threadStart:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:pBtn];
    
}

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

//-(void)btnPressed:(id)sender
//{
//    [pBtn addTarget:self action:@selector(threadStart:) forControlEvents:UIControlEventTouchUpInside];
//}
- (void)threadStart:(id)sender
{
    _firstThread = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:nil];
    [_firstThread setName:@"Thread_One"];
    [_firstThread start];
    _secondThread = [[NSThread alloc]initWithTarget:self selector:@selector(run:) object:nil];
    [_secondThread setName:@"Thread_Two"];
    [_secondThread start];
}
-(void)run:(id)sender
{
    while (TRUE) {
        [_ticketsCondition lock];
        if (_leftTickets>0) {
            [NSThread sleepForTimeInterval:0.1];
            _leftTickets--;
            _saleTickets =100-_leftTickets;
            NSString *pStr = [[NSThread currentThread]name];
            NSLog(@"售出票数是%i,剩余票数:%i,当前线程:%@",_saleTickets,_leftTickets,pStr);
        }
        else if (_leftTickets ==0){
            NSLog(@"票已售完");
            break;
        }
        
        [self performSelectorOnMainThread:@selector(updateMyview:) withObject:[[NSThread currentThread]name] waitUntilDone:YES];
        [_ticketsCondition unlock];
    }
}
- (void)updateMyview:(id)sender
{
    self.labelLeftTickets.text = [NSString stringWithFormat:@"%i",_leftTickets];
    self.labelSaleTickets.text = [NSString stringWithFormat:@"%i",_saleTickets];
    self.labelCurrentThread.text = (NSString *)sender;
    if (_leftTickets ==0) {
        UIAlertView *pAlertView = [[UIAlertView alloc]initWithTitle:@"通知" message:@"今日票已售完" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确认", nil];
        [pAlertView show];
        [pAlertView release];
        
    }
}

- (void)dealloc
{
    [_ticketsCondition release];
    [_labelLeftTickets release];
    [_labelSaleTickets release];
    [_labelCurrentThread release];
    [super dealloc];
}

@end

具体的效果图如下图所示:

抱歉!评论已关闭.