@interface ViewController (){
}
@property (nonatomic,strong) NSNumber *dataInt;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//NsThread
//[self threadDemo];
//GCD
//[self gcdDemo];
//
[self operationDemo];
}
-(void)operationDemo{
//Operation隊列
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
//設定最大的并發執行線程的數量
queue.maxConcurrentOperationCount = 4;
// 1.operation 1
//NSInvocationOperation 操作
// NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(updateUI2) object:nil];
// [operation start];
// 1.operation 2
NSBlockOperation *blockOper = [NSBlockOperation blockOperationWithBlock:^{
//這個也是更新UI的一種方式
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self updateUI];
}];
}];
//将NSBlockOperation添加到queue隊列 ,添加到隊列之後即将執行
[queue addOperation:blockOper];
// queue addOperations: NSOperation數組 waitUntilFinished:NO];
}
-(void)gcdDemo{
//擷取全局隊列的方法 第一個參數是配置設定的一個處理事務的程式優先級 0為預設 2 為高,-2為低
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
//線程異步
dispatch_async(queue, ^{
NSLog(@"線程異步");
//通知主線程重新整理界面的第一種方式 子線程不能更新UI
dispatch_async(dispatch_get_main_queue(), ^{
});
//子線程更新UI的第二種方式
[self performSelectorOnMainThread:@selector(updateUI) withObject:self waitUntilDone:YES];
NSLog(@"%@",[NSThread currentThread]);
});
//線程同步 使用串行隊列
queue = dispatch_queue_create("queue", 0);
//線程同步 第一個參數是指定一個gcd隊列 第二個參數是配置設定一個處理事務的程式到該隊列
dispatch_sync(queue, ^{
NSLog(@"線程同步");
});
}
-(void)updateUI{
//
NSLog(@"%@",[NSThread currentThread]);
UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
image.image = [UIImage imageNamed:@"car.png"];
[self.view addSubview:image];
}
-(void)updateUI2{
//
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"%@",[NSThread currentThread]);
UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
image.image = [UIImage imageNamed:@"car.png"];
[self.view addSubview:image];
});
}
-(void)threadDemo{
//1.線程等待的代碼
for (int i; i<1; i++) {
//這個是線程等待 機關是秒
[NSThread sleepForTimeInterval:1];
NSLog(@"%d",i);
}
_dataInt = [[NSNumber alloc]initWithInt:1];
// 2.建立線程的第一種方式
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(threadTest:) object:_dataInt];
[thread start];
_dataInt = [[NSNumber alloc]initWithInt:2];
// 3.建立線程的第二種方式 不需要start
[NSThread detachNewThreadSelector:@selector(threadTest:) toTarget:self withObject:_dataInt];
}
-(void)threadTest:(NSNumber *)dataInt{
NSLog(@"線程進來了%@",dataInt);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end