新建一个view-based application,
viewcontroller.h的代码如下:
#import <UIKit/UIKit.h>
@interface tConditionViewController : UIViewController {
int tickets;
NSThread *t1;
NSThread *t2;
NSCondition *tc;
}
-(void)doSomething:(id)tname;
@end
viewcontroller.m的代码如下:
#import "tConditionViewController.h"
@implementation tConditionViewController
-(void)doSomething:(id)tname
{
NSString *name = (NSString *)tname;
while (TRUE) {
NSLog(@"in thread %@", name);
[NSThread sleepForTimeInterval:1];
[tc lock];
NSLog(@"kkkk");
[tc unlock];
}
}
- (void)dealloc
{
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
tc = [[NSCondition alloc] init];
t1 = [[NSThread alloc] initWithTarget:self selector:@selector(doSomething:) object:@"1"];
[t1 start];
t2 = [[NSThread alloc] initWithTarget:self selector:@selector(doSomething:) object:@"2"];
[t2 start];
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
@end
分享到:
相关推荐
### iOS多线程编程指南知识点概述 ...本指南提供了深入理解iOS多线程编程所需的关键知识点,涵盖了从基础知识到高级技巧的各个方面。对于想要在iOS平台上开发高效、响应迅速的应用程序的开发者来说,这些内容至关重要。
在iOS和macOS的开发中,多线程同步是非常关键的一个环节,用于保证数据的一致性和安全性。在Objective-C中,我们通常会用到两种主要的互斥锁机制:NSLock和@synchronized关键字。这两个工具都用于在多线程环境下控制...
6. **NSArray线程安全**:默认不是线程安全的,需手动加锁或使用线程安全容器。 **架构:** 1. **APP架构**:MVC、MVVM、VIPER等,负责分离业务逻辑、视图和数据管理。 2. **重构页面**:分析现有结构,设计新架构...
Core Foundation的一些函数和数据结构是线程不安全的,如果在多线程环境中不加锁地访问,可能会引发数据竞争和程序崩溃。确保在并发编程中正确使用`CFRunLoop`、`CFNotificationCenter`等组件。 最后,查看`main....