//初始化線程 NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(startThread:) object: @"ios"]; thread1.name = @"thread1"; //開啟線程 [thread1 start];
通過開啟線程調用的方法 代碼
-(void)startThread:(NSString *)parm{ NSThread *currentThread = [NSThread currentThread]; for (int i=0; i<10; i++) { NSLog(@"參數為 %@, 當前的線程為 %@, 線程的名字為 %@",parm,currentThread,currentThread.name); } }
(2)靜態方法:通過類方法開啟線程,系統自動調用 代碼 [NSThread detachNewThreadSelector:@selector(startThread:) toTarget:self withObject:@"jredu"]; (3)隱式方法開啟線程 代碼 [self performSelectorInBackground:@selector(startThread:) withObject:@"apple"]; 暫停當前的線程 代碼
//方法一 [NSThread sleepForTimeInterval:2]; //方法二 NSDate *date = [NSDate dateWithTimeInterval:2 sinceDate:[NSDate date]]; [NSThread sleepUntilDate:date];
在某個線程上執行操作 (1)在指定線程執行操作 代碼 [self performSelector:@selector(run) onThread:thread1 withObject:nil waitUntilDone:YES]; (2)在主線程執行操作 代碼 [self performSelectorOnMainThread:@selector(run) withObject:nil waitUntilDone:YES]; (3)在當前線程執行操作 代碼 [self performSelector:@selector(run) withObject:nil];