售票 多线程

因为在笔者的iphone版本“售票系统多线程”程序中需要设置线程的诸多参数,所以需要采用第一种方法来生成线程对象并自己启动它们。

  首先,新建一个“Window-based Application”项目,并命名为SellTickets,接下来在SellTicketsAppDelegate.h文件中声明以下变量:

  //

  // SellTicketsAppDelegate.h

  // SellTickets

  //

  // Created by sun dfsun2009 on 09-11-10.

  // Copyright __MyCompanyName__ 2009. All rights reserved.

  //

  #import 《UIKit/UIKit.h》

  @interface SellTicketsAppDelegate : NSObject 《UIApplicationDelegate》 {

  int tickets;

  int count;

  NSThread* ticketsThreadone;

  NSThread* ticketsThreadtwo;

  UIWindow *window;

  }

  @property (nonatomic, retain) IBOutlet UIWindow *window;

  @end

  笔者在头文件中声明了两个NSThread的指针,下面需要在*.m文件中初始化并实现它们,如下:

  //

  // 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;

  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) {

  if(tickets 》 0)

  {

  [NSThread sleepForTimeInterval:0.5];

  count = 100 - tickets;

  NSLog(@“当前票数是:%d,售出:%d,线程名:%@”,tickets,count,[[NSThread currentThread] name]);

  tickets--;

  }else

  {

  break;

  }

  }

  }

  - (void)dealloc {

  [ticketsThreadone release];

  [ticketsThreadtwo release];

  [window release];

  [super dealloc];

  }

  @end

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值