iOS Development Swift (nsthread) thread-related simple instructions

Source: Internet
Author: User
Tags ticket

iOS Development Swift (nsthread) thread-related simple instructions

A description

1) The theoretical knowledge and OC implementation of the multi-threaded part is stated in the previous blog post, so it is no longer explained here.

2) This article simply explains some of the use and attention points of nsthread in the swift context.

3) This article deals with code that can be obtained from an https://github.com/HanGangAndHanMeimei/Code address.

Basic use and creation of two Nsthread

1) Basic usage (main thread | Current threads)

// 1. Get the current thread        that executes the method Let CurrentThread = nsthread.currentthread ()        print (" current thread is \ (currentthread)"  )        //2. Get the application's main thread let        mainthread = nsthread.mainthread ()        Print (" main thread of the application \ (mainthread)")        //3. Determines whether the current thread is the main path let        ismain =  nsthread.ismainthread ()

2) Create thread

Description: Four ways to create a thread are listed here:

Directly Create | Separate a child thread | Create a Background thread | The custom thread class inherits from the Nsthread override Inner Main method encapsulates the task, and then Init creates.

//Nsthread Four ways to create threadsfunc Createnewthreadwithnsthreadmethodone () {//1. Create a threadLet thread = Nsthread.init (Target:self, Selector:selector ("Run"),Object: nil)//set the name of the threadThread.Name ="Thread A"        //2. Start the threadThread.Start ()} func Createnewthreadwithnsthreadmethodtwo () {//isolate a child thread, start the thread automatically, but cannot get the thread objectNsthread.detachnewthreadselector (Selector ("Run"), Totarget:self, Withobject:nil)} func Createnewthreadwithnsthreadmethodthree () {//open a background thread, start the thread automatically, but cannot get the thread objectSelf.performselectorinbackground (Selector ("Run"), Withobject:nil); } func Createnewthreadwithnsthreadmethodfour () {//Let thread = Customthread.init (target:self, Selector:selector ("Run"), Object:nil)Let thread =Customthread (); Thread.Start ()} func run () {//gets the thread that is currently executing the Run methodLet thread =Nsthread.currentthread () print ("run--\ (thread.name)-\ (thread)"); }

Three-nsthread thread-state and thread-safe

  1) The state of the thread

Thread Status: New-ready-run-block-dead

1      // exit of the thread 2          nsthread.exit (3)         // thread of hibernation 1 4         Nsthread.sleepfortimeinterval (2.0)5         // thread hibernation 26          3.0))

2) Thread Safety

Description: Multiple threads accessing the same resource may have security issues such as data confusion, and the workaround is to lock up the necessary code snippets.

Note: In OC The mutex is used @synchronized (self) {}, the Objc_sync_enter (self) and the Objc_sync_exit (self) method can be used in swift, note that both methods must be used in pairs, Put the lock code in the middle.

classViewcontroller:uiviewcontroller {//set the total number of votes to 100 sheets    varTotaltickets = -    Overridefunc viewdidload () {super.viewdidload ()//multi-threaded access to a resource plus lock//create three threads representing conductor A, conductor B, conductor C, respectivelyLet thread01 = Nsthread.init (target:self, Selector:selector ("Saletickect"),Object: nil) let THREAD02= Nsthread.init (Target:self, Selector:selector ("Saletickect"),Object: nil); Let Thread03= Nsthread.init (Target:self, Selector:selector ("Saletickect"),Object: nil); //set the name of the threadThread01.name ="Conductor a"Thread02.name="Conductor B"Thread03.name="Conductor C"        //Open ThreadThread01.start () Thread02.start () Thread03.start ()}//function of the mock ticketfunc saletickect () { while(true)        {            //Plus mutual exclusion lock            /** 1) objc_sync_enter (self) and objc_sync_exit (self) must be used in pairs with the @synchronized (self) {} * 2) in the OC, placing the code to be locked in Middle*/Objc_sync_enter (self)//Check if there is a ticket, sell it if you have oneLet temp =totaltickets for varI=0;i<100000; i++            {                //null for loop, analog delay            }            if(temp>0) {totaltickets= Temp-1Print ("\ (Nsthread.currentthread (). Name) sold a ticket and left (totaltickets)")            }Else{print ("\ (Nsthread.currentthread (). Name) found that the tickets were sold out.")                 Break; } objc_sync_exit (Self)}}} thread-Safe code example
Thread Safety code example

Three-nsthread communication between threads

  1) Description

So-called inter-thread communication, that is, how to move from one thread to another to continue the task or to pass parameters (such as returning from a child thread to the main thread)

The following code example demonstrates creating a child thread in the main thread to download the picture, and then switch to the main thread to set the picture when the picture is downloaded.

//!! Note that the case internally downloads the image and sends an HTTP request to modify the Info.plist file    classViewcontroller:uiviewcontroller {@IBOutlet weakvarimageview:uiimageview!Overridefunc viewdidload () {super.viewdidload ()//after the program starts the sub-thread to download the picture, after the picture download completes the main thread to set the pictureNsthread.detachnewthreadselector (Selector ("Downloadimage"), Totarget:self, Withobject:nil)} func downloadimage () {//1. Get the URL of the picture you want to downloadLet URL = nsurl.init (string:"http://p9.qhimg.com/t014d1bd470cb60ac6e.jpg")        //2. Download the URL address to the resource's binary to a localLet ImageData = Nsdata.init (contentsofurl:url!)        //3. Convert binary data to imagesLet image = Uiimage.init (data:imagedata!); //4. Print to view the current thread (should be downloaded in a sub-thread)Print"current thread is \ (Nsthread.currentthread ())")        //5. Inter-thread communication//Method OneSelf.performselectoronmainthread (Selector ("ShowImage:"), Withobject:image, Waituntildone:true)        //Method Two//Imageview.performselectoronmainthread (Selector ("setimage:"), Withobject:image, waituntildone:true)} func showImage (image:uiimage) {//set up a pictureImageview.image =Image//Print View the thread that sets the picture OperationPrint"threads that handle UI refresh operations \ (Nsthread.currentthread ())")}} Inter-thread communication example code
example of inter-thread Communication code

iOS Development Swift (nsthread) thread-related simple instructions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.