1. 程式人生 > >iOS 06-多執行緒NSThread的使用

iOS 06-多執行緒NSThread的使用

1、建立一個按鈕

- (IBAction)buttonClicked:(id)sender {

NSLog(@"main =%@",[NSThreadmainThread]);

//[self createThread1];

[selfcreateThread2];

//[self createThread3];

}

-(void)createThread3 {

//開啟後臺執行緒

[selfperformSelectorInBackground:@selector(run:) withObject:@"back"];

}

-(void)createThread2{

[NSThreaddetachNewThreadSelector

:@selector(run:) toTarget:selfwithObject:@"miss"];

}

-(void)createThread1{

//建立一個執行緒

NSThread *thread = [[NSThreadalloc]initWithTarget:selfselector:@selector(run:) object:@"abc"];

thread.name = @"myThread";

//啟動執行緒

[thread start];

}

-(void)run:(id)obj {

NSLog(@"----run----%@--%@",[NSThreadcurrentThread

], obj);

//執行緒休眠

//第一種方法

[NSThreadsleepForTimeInterval:3];

//第二種方法

//[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:3]];

//或者不再執行 distantFuture(遙遠的未來)

//[NSThread sleepUntilDate:[NSDate distantFuture]];

//強制退出執行緒

for (int i = 0; i <1000000; i++) {

NSLog(@"--%d--",i);

if(i == 100) {

//執行緒退出

[NSThreadexit];

}

}

}