当前位置:网站首页>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];
}
边栏推荐
- OPENSSL ASN. 1, DER, PEM, X509
- Simple image browsing with fragment
- Path count 2 (DP + number of combinations)
- OpenGL第八章 材质material
- [cloud native] what is micro service? How to build it? Teach you how to build the first micro service (framework)
- Dépannage du problème de retard des données de communication du micro - ordinateur à puce unique
- LVGL中文字体制作
- R analysis visual practical data (flight \u education \u restaurant \u tenant \u change \u life \u safety)
- The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received
- Why is vfly, a high-end brand of Yadi that does not live up to its name, not high-end?
猜你喜欢

【ELT.ZIP】OpenHarmony啃论文俱乐部——快速随机访问字符串压缩

單片機通信數據延遲問題排查

Canvas drawing -- how to place the drawing in the center of the canvas

Understand single chip microcomputer drive 8080lcd

Artalk | how to build a domestic hyperfusion evolutionary base with minimum investment?

{dataSource-1} closing ... {dataSource-1} closed

基于SSM框架的学生在线教育教学课程管理系统

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received

If no separation ----- > > login module nanny level source code analysis (0)

iQOO 8实测上手体验:王者归来,从不高调
随机推荐
被“内卷”酸翻的OPPO Reno6
PostgreSQL source code learning (XX) -- fault recovery ① - transaction log format
OpenGl第十章 投光物
Unity's data persistence -- Jason
OPENSSL ASN.1, DER, PEM, X509
Vocabulary Construction -- code completion fast food tutorial (3) - word segmentation
JS the most commonly used sorting - hand tearing JS series
JSCPCP L. Collecting Diamonds(思维)
Promise使用
rt-thread测试
PostgreSQL source code learning (21) -- fault recovery ② - transaction log initialization
摘桃子(双指针)
canvas+svg线条粒子动画网页背景
SQL | 游戏行业部分指标
突破中国品牌创新技术实力,TCL做对了什么?
Resolved: JDBC connection to MySQL failed with an error:'The last packet sent successfully to the server was 0 milliseconds ago. '
Simple image browsing with fragment
Mazhiqiang: research progress and application of speech recognition technology -- RTC dev Meetup
Artalk | how to build a domestic hyperfusion evolutionary base with minimum investment?
WEB上传文件预览