現在感覺很不好,前幾天做的豆瓣,做不出來,沒有思路。做的時候還的看以前的代碼,太屌絲了。對不起這錢,也對不起這時間。
重點
- 獲取主線程[self performSelectorOnMainThread:@selector(referenceView) withObject:nil waitUntilDone:YES] 最後的那個參數是阻塞當前線程直到selector的那個方法執行
- 開闢一個後臺線程 [self performSelectorInBackground:@selector(cycle) withObject :nil];
- 創建一個線程
NSThread * thread = [NSThread alloc]initWithTarget:selt selector:@selector(cycle) object:nil];
- 另外一種方法創建一個線程
[NSThread detachNewThreadSelector:@selector(cycle) toTarget:selt withObject:nil]; - NSInvocationOperation創建任務,NSBlockOperation創建任務。
- 向隊列中添加任務
#import "ViewController.h"
@interface ViewController ()
- (IBAction)threadBarrage:(UIButton *)sender;
- (IBAction)multThreadOne:(UIButton *)sender;
- (IBAction)multThreadTwo:(UIButton *)sender;
- (IBAction)multiThreadThree:(UIButton *)sender;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
-(void)cycle{
//如果一個任務在子線程中執行,我們需要在任務裏面添加autoreleaspool
//因爲線程與線程之間是相互獨立的,但是呢,資源卻是共享的,在任務裏面可能會創建多個對象等等(在堆區中開闢)。如果你開闢的空間沒有釋放的話,其他的線程也無法訪問和使用
//主要針對,在子線程執行的任務中,大量使用便利構造器創建對系那個的時候,核能會造成很多堆區的對象無法釋放,導致內存泄露問題。
@autoreleasepool {
for (int i = 0 ; i< 10; i++) {
NSLog(@"%d",i);
}
//查看當前線程是否是是主線程
//判斷是是哪個線程
NSLog(@"%@",[NSThread currentThread]);
//判斷是否是主線程
NSLog(@"%d",[NSThread isMainThread]);
#warning mark ===========循環結束之後,想刷新UI界面(只能由主線程來做)
//首先要獲得主線程
[self performSelectorOnMainThread:@selector(referenceView) withObject:nil waitUntilDone:YES];
}
}
-(void)referenceView{
NSLog(@"刷新數據");
NSLog(@"%@",[NSThread currentThread]);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)threadBarrage:(UIButton *)sender {
sender.showsTouchWhenHighlighted = YES;
// [self cycle];
}
- (IBAction)multThreadOne:(UIButton *)sender {
//開闢一個後臺子線程
[self performSelectorInBackground:@selector(cycle) withObject:nil];
}
- (IBAction)multThreadTwo:(UIButton *)sender {
#warning mark ------------如果是NShread創建子線程(手動開啓)
//創建一個子線程
// NSThread * thread = [[NSThread alloc]initWithTarget:self selector:@selector(cycle) object:nil];
//
// thread.name = @"小2";
//需要手動開啓
// [thread start];
//
// [thread autorelease];
//2.NSThread創建第二種方式(線程會自動開啓)
[NSThread detachNewThreadSelector:@selector(cycle) toTarget:self withObject:nil];
}
- (IBAction)multiThreadThree:(UIButton *)sender {
#warning mark --------- 不直接使用NSOperation去創建操作對象,因爲NSOperation是一個抽象類,一般情況下,我我們使用的是其子類(NSInvocationOperation,NSBlockOperation),其子類對象放得就是每一個具體的任務
NSInvocationOperation * op1 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(cycle) object:nil];
__block ViewController * VC = self;
NSBlockOperation * op2 = [NSBlockOperation blockOperationWithBlock:^{
//需要執行的任務
[VC cycle];
}];
//只需要將操作對象放入操作隊列,不需要手動開啓,queue會根據操作對象的排列順序幫你調用start
//將上面的兩個操作對象存放到操作隊列中
NSOperationQueue * queue = [[NSOperationQueue alloc]init];
//設置線程併發數
queue.maxConcurrentOperationCount = 2;
//添加到隊列中
[queue addOperation:op1];
[queue addOperation:op2];
[op1 release];
[queue autorelease];
}
@end