GCD 队列串行 并行 同步 异步 小例

2019-01-15 14:39:57 浏览数 (1)

发现GCD Swift版有所更改,以后小例都用swift写,练习熟悉。

坚持,每天收获一点。

//

//  ViewController.swift

//  GCD_demo

//

//  Created by apple on 2017/5/31.

//  Copyright © 2017年 ZY. All rights reserved.

//

import UIKit

class ViewController: UIViewController {

overridefunc viewDidLoad() {

super.viewDidLoad()

// Do any additional setup after loading the view, typically from a nib.

concurrentQueue()

    }

overridefunc didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

// Dispose of any resources that can be recreated.

    }

//串行队列

//串行同步和异步的区别主要是:同步会阻塞线程,异步线程继续运行,耗时任务将被搁置执行

func  serialQueueDemo(){

let serialQueue  =DispatchQueue(label:"zy")//默认是串行队列

#if ture

for indexin 1..<10 {

            serialQueue.async {//不管异步还是同步都只是开辟一个线程。

                Thread.current.name? = "异步线程名字(index)"

if index==3 || index==7 {

                    Thread.sleep(forTimeInterval: 5);//

                }

                print(serialQueue.label,index,Thread.current);

            }

            print("线程阻塞了吗")

        }

#else

for indexin 1..<10 {

            serialQueue.sync {//不管异步还是同步都只是开辟一个线程。

Thread.current.name? ="同步线程名字(index)"

if index==3|| index==7 {

Thread.sleep(forTimeInterval:5);

                }

print(serialQueue.label,index,Thread.current);

            }

print("线程阻塞了吗")

        }

#endif

    }

//并发队列

func  concurrentQueue(){

let  concurrentQueyue =DispatchQueue(label: "zy.concurrent",  attributes: DispatchQueue.Attributes.concurrent)

for indexin 1..<10 {

                concurrentQueyue.async {//异步会动态开辟线程,耗时任务也会被异步执行,线程不会阻塞。

Thread.current.name? ="异步线程名字(index)"

if index==3|| index==7 {

Thread.sleep(forTimeInterval:5);//

                    }

print(concurrentQueyue.label,index,Thread.current);

                }

print("线程阻塞了吗")

            }

for indexin 1..<10 {

                concurrentQueyue.sync {//同步都只是开辟一个线程。会阻塞线程

Thread.current.name? ="同步线程名字(index)"

if index==3|| index==7 {

Thread.sleep(forTimeInterval:5);

                    }

print(concurrentQueyue.label,index,Thread.current);

                }

print("线程阻塞了吗")

            }

    }

}

小例参考:

https://github.com/RainManGO/GCD_studyDemo.git

0 人点赞