Operation(Swift)

來源:互聯網
上載者:User

標籤:art   .com   ati   cst   star   color   建立   tar   ima   

介紹:

NSOperation是一個抽象類別,並不具備封裝操作的能力,必須使用它的子類;

 

 

BlockOperation:

只要BlockOperation封裝的運算元 > 1,就會非同步執行操作,但是不會無限制的建立線程

let blockOpe = BlockOperation()        blockOpe.queuePriority = .veryHigh        blockOpe.addExecutionBlock {            print("BlockOperation執行了",Thread.current)        }        blockOpe.addExecutionBlock {            print("BlockOperation2執行了",Thread.current)        }        blockOpe.start()  //開始執行        //blockOpe.cancel() //取消

結果:

 

 

 

NSOperationQueue建立隊列

1.1 擷取主隊列以及添加操作到隊列,主隊列是串列隊列,無論是否設定最大並行數量都是在當前線程執行,不會建立新的線程

1    let queue = OperationQueue.main2         queue.addOperation {3             for _ in 0...50000{4                 print("OperationQueue1執行了",Thread.current)5             }6         }

結果:

 

2.1 同時具備串列和並發的功能,預設情況下是並發的,可以手動設定為串列隊列,通過設定最大並發數屬性來更改

1 c func racsTest() {2         let queue = OperationQueue()3         queue.maxConcurrentOperationCount = 104         queue.addOperation {5             for _ in 0...50000{6                 print("OperationQueue1執行了",Thread.current)7             }8         }9         //addOperation已經在內部執行了start方法了

結果:

 

Operation(Swift)

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.