首先,新建一个“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)applicationDidFinishLaun
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