多線程和runloop

//
// RunLoopTest.m

import "RunLoopTest.h"

import <pthread.h>

import <CoreFoundation/CFRunLoop.h>

@interface RunLoopTest() {
NSRunLoop * loop;
}
@end
@implementation RunLoopTest

  • (instancetype)init {
    if (self = [super init]) {
    // [self createThread];
    // NSLog(@"并行加同步");
    // [self DispatchQueueConcurrentAndSync];
    // [self DispatchQueueConcurrentAndAsync];

// NSLog(@"串行加同步");
// [self DispatchQueueSerialAndSync];
// [self mainQueueAndAsync];
// [self dispatchConnect];
// [self dispatchBarrierAsync];
[self dispatchGroup];
}
return self;

}

  • (void)createThread {
    // 1.Pthreads
    // pthread_t thread;
    // pthread_create(&thread, NULL, start, NULL);
    // 2.NSThread
    // NSThread * thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(thread1Run) object:nil];
    // [thread1 start];
    // 3.GCD
    dispatch_queue_t queue1 = dispatch_queue_create("test.queue", DISPATCH_QUEUE_SERIAL);//串行隊列
    dispatch_queue_t queue2 = dispatch_queue_create("test2.queue", DISPATCH_QUEUE_CONCURRENT);//并行隊列
    dispatch_sync(queue1, ^{
    // NSLog(@"同步執(zhí)行");
    });//不會開辟新的線程

    dispatch_async(queue1, ^{
    // NSLog(@"異步執(zhí)行");
    });//會開辟新的線程
    }

pragma mark -- 并行隊列 + 同步執(zhí)行

  • (void)DispatchQueueConcurrentAndSync {
    dispatch_queue_t queue1 = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);//采用全局并行隊列
    dispatch_sync(queue1, ^{
    for (int i = 0; i < 2; ++i) {
    NSLog(@"1------%@",[NSThread currentThread]);
    }
    });
    dispatch_sync(queue1, ^{
    for (int i = 0; i < 2; ++i) {
    NSLog(@"2------%@",[NSThread currentThread]);
    }
    });
    dispatch_sync(queue1, ^{
    for (int i = 0; i < 2; ++i) {
    NSLog(@"3------%@",[NSThread currentThread]);
    }
    });
    //可以預(yù)測到三個線程會按編碼的順序依次執(zhí)行字币,并且都是在主線程上執(zhí)行
    NSLog(@"syncConcurrent---end");
    }

pragma mark -- 并行隊列 + 異步執(zhí)行

  • (void)DispatchQueueConcurrentAndAsync {
    dispatch_queue_t queue1 = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);//采用全局并行隊列
    dispatch_async(queue1, ^{
    for (int i = 0; i < 2; ++i) {
    NSLog(@"1------%@",[NSThread currentThread]);
    }
    });
    dispatch_async(queue1, ^{
    for (int i = 0; i < 2; ++i) {
    NSLog(@"2------%@",[NSThread currentThread]);
    }
    });
    dispatch_async(queue1, ^{
    for (int i = 0; i < 2; ++i) {
    NSLog(@"3------%@",[NSThread currentThread]);
    }
    });
    //可以預(yù)測到先打印的是@"asyncConcurrent---end"洗出,因為這個方法是在主線程上執(zhí)行,等級高于異步開的子線程翩活,然后打印3個子線程菠镇,并且三個子線程打印的順序是不固定,因為是并行隊。所以異步線程并不影響主線程
    NSLog(@"asyncConcurrent---end");
    }

pragma mark -- 串行隊列 + 異步執(zhí)行

  • (void)DispatchQueueSerialAndAsync {
    // 會開啟新線程辟犀,但是因為任務(wù)是串行的,執(zhí)行完一個任務(wù)魂毁,再執(zhí)行下一個任務(wù)
    dispatch_queue_t queue1 = dispatch_queue_create("test1.queue1", DISPATCH_QUEUE_SERIAL);
    dispatch_async(queue1, ^{
    for (int i = 0; i < 2; ++i) {
    NSLog(@"1------%@",[NSThread currentThread]);
    }
    });
    dispatch_async(queue1, ^{
    for (int i = 0; i < 2; ++i) {
    NSLog(@"2------%@",[NSThread currentThread]);
    }
    });
    dispatch_async(queue1, ^{
    for (int i = 0; i < 2; ++i) {
    NSLog(@"3------%@",[NSThread currentThread]);
    }
    });
    //可以預(yù)測到先打印的是@"asyncConcurrent---end"出嘹,因為這個方法是在主線程上執(zhí)行税稼,等級高于異步開的子線程垮斯,然后打印按順序依次執(zhí)行3個子線程里面的方法只祠,并且三個子線程打印順序是固定,因為是串行隊列抛寝。所以異步線程并不影響主線程
    NSLog(@"asyncSerial---end");
    }

pragma mark -- 串行隊列 + 同步執(zhí)行

  • (void)DispatchQueueSerialAndSync {
    // 不會開啟新線程盗舰,執(zhí)行完一個任務(wù),再執(zhí)行下一個任務(wù)
    dispatch_queue_t queue1 = dispatch_queue_create("test1.queue1", DISPATCH_QUEUE_SERIAL);
    dispatch_sync(queue1, ^{
    for (int i = 0; i < 2; ++i) {
    NSLog(@"1------%@",[NSThread currentThread]);
    }
    });
    dispatch_sync(queue1, ^{
    for (int i = 0; i < 2; ++i) {
    NSLog(@"2------%@",[NSThread currentThread]);
    }
    });
    dispatch_sync(queue1, ^{
    for (int i = 0; i < 2; ++i) {
    NSLog(@"3------%@",[NSThread currentThread]);
    }
    });
    NSLog(@"syncSerial---end");
    //可以預(yù)測到三個線程會按編碼的順序依次執(zhí)行川陆,并且都是在主線程上執(zhí)行

}

pragma mark -- 主隊列 + 同步執(zhí)行

  • (void)mainQueueAndSync {
    NSLog(@"syncMain---begin");

    // 互等卡住不可行(在主線程中調(diào)用)
    dispatch_queue_t queue1 = dispatch_get_main_queue();
    dispatch_sync(queue1, ^{
    for (int i = 0; i < 2; ++i) {
    NSLog(@"1------%@",[NSThread currentThread]);
    }
    });
    dispatch_sync(queue1, ^{
    for (int i = 0; i < 2; ++i) {
    NSLog(@"2------%@",[NSThread currentThread]);
    }
    });
    dispatch_sync(queue1, ^{
    for (int i = 0; i < 2; ++i) {
    NSLog(@"3------%@",[NSThread currentThread]);
    }
    });
    NSLog(@"syncMain---end");
    //可以預(yù)測到三個線程會按編碼的順序依次執(zhí)行蛮位,并且都是在主線程上執(zhí)行

}

pragma mark -- 主隊列 + 異步執(zhí)行

  • (void)mainQueueAndAsync {
    NSLog(@"asyncMain---begin");

    dispatch_queue_t queue1 = dispatch_get_main_queue();
    dispatch_async(queue1, ^{
    for (int i = 0; i < 2; ++i) {
    NSLog(@"1------%@",[NSThread currentThread]);
    }
    });
    dispatch_async(queue1, ^{
    for (int i = 0; i < 2; ++i) {
    NSLog(@"2------%@",[NSThread currentThread]);
    }
    });
    dispatch_async(queue1, ^{
    for (int i = 0; i < 2; ++i) {
    NSLog(@"3------%@",[NSThread currentThread]);
    }
    });
    NSLog(@"asyncMain---end");

}

pragma mark -- GCD線程之間的通訊

  • (void)dispatchConnect {

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    for (int i = 0; i < 2; i ++) {
    NSLog(@"1------%@",[NSThread currentThread]);
    }
    dispatch_async(dispatch_get_main_queue(), ^{
    for (int i = 0; i < 2; i ++) {
    NSLog(@"2------%@",[NSThread currentThread]);
    }
    });
    });

// 先進(jìn)行子線程的操作土至,然后回到主線程進(jìn)行下一步操作
}

pragma mark -- GCD的柵欄方法 dispatch_barrier_async

  • (void)dispatchBarrierAsync {
    dispatch_queue_t queue = dispatch_queue_create("12323", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
    NSLog(@"1------%@",[NSThread currentThread]);
    });
    dispatch_async(queue, ^{
    NSLog(@"2------%@",[NSThread currentThread]);
    });

    dispatch_barrier_async(queue, ^{
    NSLog(@"等一會在進(jìn)行后面的答應(yīng)---%@",[NSThread currentThread]);
    });
    dispatch_async(queue, ^{
    NSLog(@"3------%@",[NSThread currentThread]);
    });
    dispatch_async(queue, ^{
    NSLog(@"4------%@",[NSThread currentThread]);
    });

}

pragma mark -- GCD的隊列組 dispatch_group

  • (void)dispatchGroup {
    dispatch_group_t group1 = dispatch_group_create();
    dispatch_group_async(group1, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    //耗時操作1
    NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    loop = [NSRunLoop currentRunLoop];
    [loop addTimer:timer forMode:NSRunLoopCommonModes];
    [loop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:10.0]]; //主線程等待陶因,但讓出主線程時間片,然后過10秒后返回

    });
    dispatch_group_async(group1, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    //耗時操作2
    NSTimer * timer1 = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    loop = [NSRunLoop currentRunLoop];
    [loop addTimer:timer1 forMode:NSRunLoopCommonModes];
    [loop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:5.0]]; //主線程等待楷扬,但讓出主線程時間片烘苹,然后過10秒后返回

    });
    // 等上面的耗時操作都完成了,再回到主線程

    dispatch_group_notify(group1, dispatch_get_main_queue(), ^{
    NSLog(@"3");
    });
    }

  • (void)timerAction {
    NSLog(@"%@",[NSThread currentThread]);
    }

  • (void)thread1Run {

}
//static CFSpinlock_t loopsLcok;
@end

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末霜定,一起剝皮案震驚了整個濱河市廊鸥,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌惰说,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,997評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件典挑,死亡現(xiàn)場離奇詭異,居然都是意外死亡拙寡,警方通過查閱死者的電腦和手機(jī)顾犹,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,603評論 3 392
  • 文/潘曉璐 我一進(jìn)店門褒墨,熙熙樓的掌柜王于貴愁眉苦臉地迎上來郁妈,“玉大人,你說我怎么就攤上這事噩咪。” “怎么了涨享?”我有些...
    開封第一講書人閱讀 163,359評論 0 353
  • 文/不壞的土叔 我叫張陵仆百,是天一觀的道長。 經(jīng)常有香客問我吁讨,道長峦朗,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,309評論 1 292
  • 正文 為了忘掉前任翎朱,我火速辦了婚禮尺铣,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘迄埃。我一直安慰自己,他們只是感情好蕉汪,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,346評論 6 390
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著福澡,像睡著了一般驹马。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上糯累,一...
    開封第一講書人閱讀 51,258評論 1 300
  • 那天泳姐,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛渠旁,可吹牛的內(nèi)容都是我干的躲查。 我是一名探鬼主播,決...
    沈念sama閱讀 40,122評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼蚂蕴,長吁一口氣:“原來是場噩夢啊……” “哼俯邓!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起稽鞭,我...
    開封第一講書人閱讀 38,970評論 0 275
  • 序言:老撾萬榮一對情侶失蹤朦蕴,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后吩抓,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,403評論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡伴栓,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,596評論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了惑淳。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片饺窿。...
    茶點(diǎn)故事閱讀 39,769評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖绢馍,靈堂內(nèi)的尸體忽然破棺而出肠套,到底是詐尸還是另有隱情,我是刑警寧澤糠排,帶...
    沈念sama閱讀 35,464評論 5 344
  • 正文 年R本政府宣布入宦,位于F島的核電站室琢,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏盈滴。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,075評論 3 327
  • 文/蒙蒙 一病苗、第九天 我趴在偏房一處隱蔽的房頂上張望症汹。 院中可真熱鬧,春花似錦背镇、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,705評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至蔑鹦,卻和暖如春夺克,著一層夾襖步出監(jiān)牢的瞬間嚎朽,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,848評論 1 269
  • 我被黑心中介騙來泰國打工狡门, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留锅很,地道東北人。 一個月前我還...
    沈念sama閱讀 47,831評論 2 370
  • 正文 我出身青樓叛复,卻偏偏與公主長得像扔仓,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子翘簇,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,678評論 2 354

推薦閱讀更多精彩內(nèi)容