1. An overview of the

Threads are useful when performing a time-consuming operation that does not want to affect the main thread, which is when multithreading is needed to improve application performance and enhance the user experience. This article will describe one of the iOS threads. Let’s take a look.

As a developer, it’s especially important to have a learning atmosphere and a networking community, and this is one of my iOS networking groups:812157648, no matter you are small white or big ox welcome to enter, share BAT, Ali interview questions, interview experience, discuss technology, we exchange learning growth together!

2. Create a Thread

Available (iOS 2.0, *) public convenience init(target: Any, selector: selector, object argument: Any?) @ Available (iOS 10.0, *) public Convenience init(block: @escaping () -> Void) @available(iOS 10.0, *) Open Class func detachNewThread(_ block: @escaping () -> Void) open class func detachNewThreadSelector(_ selector: Selector, toTarget target: Any, with argument: Any?)Copy the code

Of the above methods, the first two are object initializers that return a Thread object, while the last two are class methods that directly start a child Thread.

Here’s a set of tests:

	func createThread() {
        let thread1 = Thread(target: self, selector: #selector(threadMethod1), object: nil)
        let thread2 = Thread {
            print("thread2 \(Thread.current)")
        }
        thread1.start()
        thread2.start()
        
        Thread.detachNewThreadSelector(#selector(threadMethod3), toTarget: self, with: nil)
        Thread.detachNewThread {
            print("thread4 \(Thread.current)")
        }
    }
    @objc func threadMethod1() {
        print("thread1 \(Thread.current)")
    }
    @objc func threadMethod3() {
        print("thread3 \(Thread.current)")
    }
Copy the code

After running, we get:

thread4 <NSThread: 0x600002284600>{number = 9, name = (null)}
thread2 <NSThread: 0x600002284540>{number = 7, name = (null)}
thread1 <NSThread: 0x600002284500>{number = 6, name = (null)}
thread3 <NSThread: 0x600002284580>{number = 8, name = (null)}
Copy the code

The Thread object obtained by initializing the object needs to call the start() method to start the child Thread, which is set to a ready state, waiting for the CPU to schedule it. The two child threads opened by class methods do not return Thread objects and are created ready without the need for the start() method.

3. Common attributes and methods of Thread

List of common attributes:

The attribute name type describe
class var current: Thread { get } Thread Returns the current thread object.
class var isMainThread: Bool { get } Bool Whether the current thread is the master thread.
class var main: Thread { get } Thread Returns the main thread object.
var threadPriority: Double Double The value ranges from 0.0 to 1.0. The default value is 0.5. A higher value indicates a higher priority
var name: String? String Thread name.
var isMainThread: Bool { get } Bool Whether the thread is the master thread.
var isExecuting: Bool { get } Bool Whether the thread is executing.
var isFinished: Bool { get } Bool Whether the thread is terminated.
var isCancelled: Bool { get } Bool Whether the thread has been marked cancelled.

List of common class methods and instance methods:

Method names Return value type describe
class func isMultiThreaded() -> Bool Bool Is it multithreading?
class func sleep(until date: Date) Void The thread blocks for a certain time.
class func sleep(forTimeInterval ti: TimeInterval) Void The thread blocks for a period of time.
class func exit() Void Exit the current thread, do not call from the main thread, otherwise the program crashes.
class func threadPriority() -> Double Double Gets the thread priority.
class func setThreadPriority(_ p: Double) -> Bool Bool The value ranges from 0.0 to 1.0. The default value is 0.5. A higher priority indicates a higher priority.
func cancel() Void Marks the thread as cancelled.
func start() Void Start the thread.

4. Thread Common attributes and methods

Override func viewDidLoad() {super.viewdidLoad () // set the main Thread name thread.main. name = "MainThread" threadTestDemo()} func ThreadTestDemo () {myThread = Thread(target: self, selector: #selector(myThreadMethod), object: Nil) // set the child thread name myThread?. Name = "myThread" // set the child threadPriority myThread?. ThreadPriority = 1.0 // start the child thread myThread? Thread. Sleep (forTimeInterval: If let thread = myThread {print("3 seconds later, myThread is executing: \(thread.isExecuting)") print("3 seconds later, myThread is finished : \(thread.isfinished)")}} @objc func myThreadMethod() {print(" thread is: \(thread.main)") // Print ("Current Thread is: \(thread.current)") print(" current Thread is main Thread: \(Thread. IsMainThread)") if Thread = myThread {// print("myThread name is: \(String(describing:) Print ("myThread priority is: \(thread.threadpriority)") print("myThread is main thread: \(thread.ismainThread)") // If a subthread is executing a print("myThread is executing: \(thread.isexecuting)") // Whether the child thread is cancelled: \(thread.iscancelled)") // Whether the child thread is terminated. Print ("myThread is finished: \(thread.isfinished)")} Repeats: true) {(timer) in print(" timer is running")}} > > < span style = "font-size: 16px; RunLoop.current.run() */ }Copy the code

The thread method annotates the Timer method, which runs as follows:

Main thread is : <NSThread: 0x600000d80400>{number = 1, name = MainThread} Current thread is : <NSThread: 0x600000dcd040>{number = 7, name = MyThread} Current thread is main thread : false myThread name is : Optional("MyThread") MyThread Priority is: 1.0 MyThread is main thread: false MyThread is executing: true myThread is cancelled : false myThread is finished : false 3 seconds later, myThread is executing : false 3 seconds later, myThread is finished : trueCopy the code

In the above result: the child thread finishes running after 3 seconds.

If the Timer comment code is opened, the result is as follows:

Main thread is : <NSThread: 0x600002c6c980>{number = 1, name = MainThread} Current thread is : <NSThread: 0x600002c5f000>{number = 7, name = MyThread} Current thread is main thread : false myThread name is : Optional("MyThread") MyThread Priority is: 1.0 MyThread is main thread: false MyThread is executing: true myThread is cancelled : false myThread is finished : false Timer is running Timer is running Timer is running 3 seconds later, myThread is executing : true 3 seconds later, myThread is finished : false Timer is running Timer is runningCopy the code

The result of both runs is whether the thread is still executing after 3 seconds.

5. NSObject Extends the Thread method

Some NSObject methods for extending threads:

open func performSelector(onMainThread aSelector: Selector, with arg: Any? , waitUntilDone wait: Bool, modes array: [String]?) open func performSelector(onMainThread aSelector: Selector, with arg: Any? , waitUntilDone wait: Bool) open func perform(_ aSelector: Selector, on thr: Thread, with arg: Any? , waitUntilDone wait: Bool, modes array: [String]?) open func perform(_ aSelector: Selector, on thr: Thread, with arg: Any? , waitUntilDone wait: Bool) open func performSelector(inBackground aSelector: Selector, with arg: Any?)Copy the code

6. Conclusion

Thread is a lightweight multithreading method in iOS, and it is relatively easy to use. There are also two main multithreading methods, GCD and Operation, which will be introduced in the next article. Please pay attention to them.

Daniel_Coder

The original address: blog.csdn.net/guoyongming…