当前位置:网站首页>Nsthread of the multithreaded Trilogy
Nsthread of the multithreaded Trilogy
2022-06-11 03:35:00 【chabuduoxs】
NSThread What is it? ?
As we all know iOS There are four main ways of multithreading development ,NSThread That's one of them .
Here is apple Official explanation 
It can be seen that NSThread yes apple A thread class encapsulated , Developers can operate on threads , And you can monitor thread status .NSThread Is based on thread usage , Lightweight multithreaded programming method ( relative GCD and NSOperation), One NSThread Object represents a thread
NSThread Use
NSThread The creation of
The creation method of this class is relatively simple , It can be roughly divided into dynamic and static methods .
- 1. You can create... Dynamically ( Example method ) initialization NSThread object , You need to call - (void)start Method to start the thread .
// Parameter meaning
/*target selector The object to which the specified message is sent . selector To send a message to target Selector . This selector must accept only one parameter , And must not have a return value . argument A single parameter passed to the target . May be nil. */
NSThread *firstThread = [[NSThread alloc] initWithTarget:self selector:@selector(sellTicket:) object:nil];
firstThread.name = @"thread1";
[firstThread start];
- 2. It can also be done through NSThread Static method of ( Class method ) Quickly create and automatically start new threads
// Detach New Threads , And use the specified selector as the thread entry point .
[NSThread detachNewThreadSelector:@selector(pressBack:) toTarget:self withObject:@"thread4"];
- 3. Besides NSObject Base class objects also provide implicit quick creation performSelector, Automatically start a new thread
[self performSelectorInBackground:@selector(threadRun) withObject:@"thread5"];
Some threads communicate
// The current thread performs an operation
// [self performSelector:@selector(threadRun)];
// [self performSelector:@selector(threadRun) withObject:@"thread6"];
// // Delay n Enter the thread in seconds
// [self performSelector:@selector(threadRun) withObject:@"thread7" afterDelay:2.0];
// // Specify the main thread operation in other threads
// [self performSelectorOnMainThread:@selector(threadRun) withObject:nil
// waitUntilDone:YES];
// // ( In the main thread ) Specify another thread to perform the operation
// [self performSelector:@selector(threadRun) onThread:thread1
// withObject:nil waitUntilDone:YES];
// wait by YES You need to wait for the main thread to operate ,NO The child thread does not have to wait
// // It is specified here as a thread
// [self performSelectorInBackground:@selector(threadRun) withObject:nil];
// This is designated as the background thread
NSThread Some properties of

A simple example , Ticket handling
Suppose we need to sell 100 movie tickets , We opened three windows at the same time at the ticket office
{
// Thread synchronization problem :
NSThread *firstThread = [[NSThread alloc] initWithTarget:self selector:@selector(sellTicket:) object:nil];
firstThread.name = @"thread1";
NSThread *secondThread = [[NSThread alloc] initWithTarget:self selector:@selector(sellTicket:) object:nil];
secondThread.name = @"thread2";
NSThread *thirdThread = [[NSThread alloc] initWithTarget:self selector:@selector(sellTicket:) object:nil];
thirdThread.name=@"thread3";
[firstThread start];
[secondThread start];
[thirdThread start];
[NSThread currentThread];
// while(1) {
// NSThread* thread = [[NSThread alloc] initWithTarget:self selector:@selector(sellTicket:) object:nil];
// [thread start];
// }
}
- (void)sellTicket:(NSThread*) thread {
while (self.ticketsCount > 0) {
NSThread *thread = [NSThread currentThread];// Get the current thread
[NSThread sleepForTimeInterval:2];
self.ticketsCount -- ;
NSLog(@" Current thread :%@\n The number of votes left is :%d ",thread.name, self.ticketsCount);
}
}
So let's see what happens , The data will be confused , This is because we have not implemented thread synchronization , It causes competition for resources .
Now we can realize thread synchronization :
- The first way
@synchronized( object )Key words areThe mutex, When a new thread accesses , If you find that other threads are executing locked code , A new thread entersSleep.
- (void)sellTicket:(NSThread*) thread {
while (self.ticketsCount > 0) {
@synchronized(self) {
NSThread *thread = [NSThread currentThread];
[NSThread sleepForTimeInterval:2];
self.ticketsCount -- ;
NSLog(@" Current thread :%@\n The number of votes left is :%d ",thread.name, self.ticketsCount);
}
}
}
- You can also use NSLock
NSLock yes Cocoa Provide us with the most basic lock object , It's also often used , except lock and unlock Outside method ,NSLock It also provides tryLock and lockBeforeDate: Two methods , The previous method tries to lock , If the lock is not available ( It's locked ), It doesn't block threads , Go straight back to NO.lockBeforeDate: Method will be specified in the Date Try locking before , If you cannot lock before the specified time , Then return to NO.
self.threadLock = [[NSLock alloc]init];
while (self.ticketsCount > 0) {
[self.threadLock lock];
//[self.condition lock];
NSThread *thread = [NSThread currentThread];
[NSThread sleepForTimeInterval:2];
self.ticketsCount -- ;
NSLog(@" Current thread :%@\n The number of votes left is :%zd ",thread.name, self.ticketsCount);
[self.threadLock unlock];
//[self.condition unlock];
}
边栏推荐
- 对象存储Minio使用教程
- Troubleshooting of single chip microcomputer communication data delay
- 【安全科普】挖矿技术,从一个理工男的爱情故事讲起
- 名不副实的雅迪高端品牌VFLY,为何“不高端”?
- Jscpcp L. collecting diamonds (thinking)
- What has TCL done right to break through the technological strength of Chinese brand innovation?
- Technology Pro strength evaluation: comprehensive PK of high-end massage chair market, who is worthy of the machine king?
- OpenGL第十一章 多光源
- js实现柯里化
- JS top icon menu click to switch background color JS special effect
猜你喜欢

618将至!全渠道开售,高价低配的OPPO Reno6能赢吗?

UML series articles (28) architecture modeling - collaboration

用Fragment实现图片简易浏览

Product milestones in May 2022

PostgreSQL source code learning (XX) -- fault recovery ① - transaction log format

Canvas rotation drawing H5 animation JS effect

net::ERR_ FILE_ NOT_ Found error

Iqoo 8 measured hands-on experience: return of the king, never high profile

If not, use the code generator to generate a set of addition, deletion, modification and query (2)

基于SSM框架的学生在线教育教学课程管理系统
随机推荐
J. Balanced Tree
How should Xiaobai start the Amazon self support evaluation?
基于SSM框架的连锁超市购物零售后台管理系统
多线程四部曲之NSThread
HikariPool-1 - Shutdown initiated... HikariPool-1 - Shutdown completed.
If no separation ----- > > login module nanny level source code analysis (0)
联易融一面(已过)
Canvas+svg line particle animation web page background
Rhel7 switch character encoding to GBK
openssl enc 加解密
Shangpinhui mall_ Background homepage of
RT thread test
【ELT.ZIP】OpenHarmony啃论文俱乐部——电子设备软件更新压缩
OpenGl第九章 光照贴图
【安全科普】挖矿技术,从一个理工男的爱情故事讲起
rt-thread测试
PostgreSQL source code learning (17) -- mvcc ② - Introduction to snapshot and isolation level
Computer vision (AI) interview
UML系列文章(28)体系结构建模---协作
Canvas interactive star animation background JS special effect