標籤:ios開發 ios線程 多線程
// 建立線程方式1
- (void)test1
{
// 執行個體化一個線程對像 NSThread *thread = [[NSThreadalloc] initWithTarget:self selector:@selector(run) object:nil]; // 讓線程開始工作,啟動線程, 在新開的線程執行run方法 [threadstart];}
// 建立線程方式2
- (void)test2
{
NSLog(@"---%@", [NSThreadcurrentThread]); [NSThreaddetachNewThreadSelector:@selector(run:)toTarget:selfwithObject:@"hello"];}
// 建立線程方式3
- (void)test3
{
// “隱式”建立線程方式
[selfperformSelectorInBackground:@selector(run:)withObject:@"cz"];}
#pragma mark - 線程的屬性
- (void)test4
{ NSThread *threadA = [[NSThreadalloc] initWithTarget:self selector:@selector(run:) object:@"hello"]; threadA.name= @"thraed A";
// 線程優先順序
// 是一個浮點數,0.0~1.0。 預設值 0.5
// 開發的時候,一般不去修改優先順序的值。
// 優先順序,必須調用很多次的時候,才能體現出來。 threadA.threadPriority =0.1;
// 開始工作 [threadAstart];}
// NSThread線程的狀態
- (void)run
{
NSLog(@"%s", __func__);
// 剛進來就睡會, 睡2秒
// [NSThread sleepForTimeInterval:5.0];
// 睡到指定的時間點
// [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:5.0]];
for (inti = 0; i < 20; i++) {
// 滿足某一個條件以後,阻塞線程的執行。 也就是讓線程休息一會
if (i ==10) {
[NSThreadsleepForTimeInterval:3.0];
}
// 一旦達到某一個條件,就強制終止線程的執行
if (i ==15) {
// 一旦強制終止,就在不能重新啟動
// 一旦強制終止,後面的代碼都不會執行
[NSThreadexit];
}
NSLog(@"%@--- %d", [NSThreadcurrentThread], i);
}
NSLog(@"線程結束");
}
// 把資料傳到主線程,在主線程更新UI 1.[selfperformSelectorOnMainThread:@selector(downloadFinish:)withObject:imagewaitUntilDone:NO];
2. [selfperformSelector:@selector(downloadFinish:) onThread:[NSThread mainThread] withObject:image waitUntilDone:NO];
3.[self.iconView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];
// nonatomic 非原子屬性
// atomic 原子屬性--預設屬性
// 原子屬性就是針對多線程設計的。 原子屬性實現 單(線程)寫 多(線程)讀// 因為寫的安全層級要求更高。 讀的要求低一些,可以多讀幾次來保證資料的正確性
// 原子屬性內部使用的 自旋鎖
// 自旋鎖和互斥鎖
// 共同點: 都可以鎖定一段代碼。 同一時間, 只有線程能夠執行這段鎖定的代碼
// 區別:互斥鎖,在鎖定的時候,其他線程會睡眠,等待條件滿足,再喚醒 // 自旋鎖,在鎖定的時候, 其他的線程會做死迴圈,一直等待這條件滿足,一旦條件滿足,立馬去執行,少了一個喚醒過程
IOS多線程開發-NSThread原理及示範