NSThread 为objective-c 的多线程对象
#import "Saler.h"
@implementation Saler
-(Saler*) init{
self = [super init];
NSLog(@"init saler");
self.ticket = [NSNumber numberWithInt:20];
return self;
}
-(void) startSale{
NSThread *thread = [NSThread new];
self->thread = thread;
[thread initWithTarget:self selector:@selector(run) object:nil];
//该访问指明调用self.run 方法作为线程运行代码
[thread start];
}
-(void) run{
NSLog(@"running");
}
@end
main 函数
#import <Foundation/Foundation.h>
#import "Saler.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Saler* saler1 = [Saler new];
Saler* saler2 = [Saler new];
[saler1 startSale];
[saler2 startSale];
NSLog(@"starting");
}
return 0;
}
console output
2023-04-02 20:58:33.568419+0800 CMD[2079:186178] init saler
2023-04-02 20:58:33.568662+0800 CMD[2079:186178] init saler
2023-04-02 20:58:33.569828+0800 CMD[2079:186178] starting
2023-04-02 20:58:33.570763+0800 CMD[2079:186233] running
2023-04-02 20:58:33.570776+0800 CMD[2079:186234] running
Program ended with exit code: 0