I. Implementation results
In this program, seven controls, three descriptive labels, three output ports, and one button are used.
Ii. Code attributes
Attributes used: Three output labels and one button
One button Method
# Import
@ Interface WeSecondThreadViewController: UIViewController
{// Remaining votes and sold votes
Int _ leftTicks;
Int _ saledTicks;
// Two threads
NSThread * _ firstThread;
NSThread * _ secondThread;
// Lock Condition
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
Iii. method implementation
// Initialize the remaining number of votes and number of sold votes
-(Void) viewDidLoad
{
[Super viewDidLoad];
_ LeftTicks = 100;
_ SaledTicks = 0;
_ TicksConfition = [[NSCondition alloc] init];
// Do any additional setup after loading the view from its nib.
}
// Response method of the button
-(IBAction) startAction :( id) sender
{
// Start with a thread
_ FirstThread = [[NSThread alloc] initWithTarget: self selector: @ selector (startThread :) object: nil];
[_ FirstThread setName: @ Thread_1];
[_ FirstThread start];
// Start with thread 2
_ SecondThread = [[NSThread alloc] initWithTarget: self selector: @ selector (startThread :) object: nil];
[_ SecondThread setName: @ Thread_2];
[_ SecondThread start];
}
-(Void) startThread :( id) sender
{
While (TRUE)
{
// Thread lock to enable interaction between two threads
[_ TicksConfition lock];
If (_ leftTicks> 0)
{
[NSThread sleepForTimeInterval: 0.1];
_ LeftTicks --;
_ SaledTicks = 100-_ leftTicks;
NSString * pstr = [[NSThread currentThread] name];
NSLog (@ sold votes: % I remaining votes % I current thread % @, _ saledTicks, _ leftTicks, pstr );
}
Else if (_ leftTicks = 0)
{
NSLog (@ ticket sold out );
Break;
}
// Update in the main thread
[Self initialize mselecw.mainthread: @ selector (updateMyView :) withObject: [[NSThread currentThread] name] waitUntilDone: YES];
// Unlock
[_ TicksConfition unlock];
}
}
// Update on the screen
-(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: @ notification message: @ delegate: nil cancelButtonTitle: nil otherButtonTitles: @ OK, nil];
[PAlter show];
[PAlter release];
}
}
Demo related: http://download.csdn.net/detail/u012887301/6777319