使用操作对象的简单例子(63)

来源:互联网 发布:python能用来做什么 编辑:程序博客网 时间:2024/06/07 00:28
#import <Foundation/Foundation.h>#import <stdio.h>#import <stdlib.h>#import <unistd.h>NSMutableArray *MyList;@interface MyOperation : NSOperation {    int number;  //各任务号    NSTimeInterval interval;  //时间间隔}- (id)initWithNum:(int)sn;- (void)main;@end@implementation MyOperation- (id)initWithNum:(int)sn {    if ((self = [super init]) != nil) {        number = sn;        interval = (double)(random() & 0x7f) / 256.0; //生成少于0.5秒的随机值。    }    return self;}- (void)dealloc {    NSLog(@"Realease: %d", number);}- (void)main {    @try {        @autoreleasepool {            NSNumber *obj = [NSNumber numberWithInt:number];            [NSThread sleepForTimeInterval:interval];            @synchronized(MyList) {                [MyList addObject:obj];            }        }    }    @catch(...) {/*只捕捉异常,不做任何操作*/}}@endint main(void) {    const int Tasks = 10;    srandom((unsigned)getpid());  //随机数种子        @autoreleasepool {        int i;        NSOperationQueue *queue = [[NSOperationQueue alloc] init];        MyList = [[NSMutableArray alloc] init];                for (i = 0; i < Tasks; i++) { //创建操作,添加到队列中            NSOperation *opr = [[MyOperation alloc] initWithNum:i];            [queue addOperation:opr];    }        [NSThread sleepForTimeInterval:2.0];  //等待终止        for (id obj in MyList)            printf(" %d", [obj intValue]);        printf("\n");}    return 0;}




0 0
原创粉丝点击