[Xcode10 实际操作]八、网络与多线程-(23)多线程的同步与异步的区别

本文将演示线程的同步与异步的区别。

在项目导航区,打开视图控制器的代码文件【ViewController.swift】

异步线程的运行,是没有按照顺序执行的。

 1 import UIKit
 2 
 3 class ViewController: UIViewController {
 4 
 5     override func viewDidLoad() {
 6         super.viewDidLoad()
 7         // Do any additional setup after loading the view, typically from a nib.
 8         
 9         //创建一个异步线程,异步线程的运行,是没有按照顺序执行的。
10         DispatchQueue.global(qos:.default).async
11         {
12             //添加一个执行4次的循环语句
13             for i in 0 ..< 4
14             {
15                 //在控制台打印输出日志信息,
16                 print("Talking something:\(i)")
17                 //并使线程休眠1秒钟,以方便观察线程的运行
18                 sleep(1)
19             }
20         }
21         
22         //继续创建一个异步线程,
23         DispatchQueue.global(qos:.default).async
24         {
25             //添加一个执行4次的循环语句
26             for i in 0 ..< 4
27             {
28                 //在控制台打印输出不同的日志信息,
29                 print("Watching TV:\(i)")
30                 //并使线程休眠1秒钟,以方便观察线程的运行
31                 sleep(1)
32             }
33         }
34     }
35 
36     override func didReceiveMemoryWarning() {
37         super.didReceiveMemoryWarning()
38         // Dispose of any resources that can be recreated.
39     }
40 }

将异步线程方法(async),更改为同步线程方法(sync)。

同步线程的运行,是按照顺序依次执行的。

 1 import UIKit
 2 
 3 class ViewController: UIViewController {
 4 
 5     override func viewDidLoad() {
 6         super.viewDidLoad()
 7         // Do any additional setup after loading the view, typically from a nib.
 8         
 9         //创建一个同步线程,同步线程的运行,是按照顺序依次执行的。
10         DispatchQueue.global(qos:.default).sync
11         {
12             //添加一个执行4次的循环语句
13             for i in 0 ..< 4
14             {
15                 //在控制台打印输出日志信息,
16                 print("Talking something:\(i)")
17                 //并使线程休眠1秒钟,以方便观察线程的运行
18                 sleep(1)
19             }
20         }
21         
22         //继续创建一个同步线程,
23         DispatchQueue.global(qos:.default).sync
24         {
25             //添加一个执行4次的循环语句
26             for i in 0 ..< 4
27             {
28                 //在控制台打印输出不同的日志信息,
29                 print("Watching TV:\(i)")
30                 //并使线程休眠1秒钟,以方便观察线程的运行
31                 sleep(1)
32             }
33         }
34     }
35 
36     override func didReceiveMemoryWarning() {
37         super.didReceiveMemoryWarning()
38         // Dispose of any resources that can be recreated.
39     }
40 }

猜你喜欢

转载自www.cnblogs.com/strengthen/p/10074826.html