標籤:
小編在此之前,通過一個小例子,簡單的形容了一下進程與線程之間的關係,現在網路編程中的多線程說一下!!!
*進程的基本概念
每一個進程都是一個應用程式,都有自己獨立的記憶體空間,一般來說一個應用程式存在一個進程,但也有多個進程的情況;
同一個進程中的線程共用記憶體中記憶體和資源。
*線程的基本概念
每一個程式都有一個主線程,程式啟動時建立(調用main來啟動)。主線程的生命週期是和應用程式綁定的,程式退出(結束)時,主線程也就停止了。多線程技術表示,一個應用程式都多個線程,使用多線程能提供CPU的使用率,防止主線程堵塞。任何有可能堵塞主線程的任務不要在主線程中執行。
########################建立多線程的方法#########################
//第一種建立方法
NSThread *mainThread = [[NSThread alloc]initWithTarget:self selector:@selector(mutableThread:) object:nil];
[mainThread start];
//第二種建立方式
[NSThread detachNewThreadSelector:@selector(mutableThread:) toTarget:self withObject:nil];
//第三種建立方式
[self performSelectorInBackground:@selector(mutableThread:) withObject:nil];
//第四種建立方式
NSOperationQueue *operationQueue = [[NSOperationQueue alloc]init];
[operationQueue addOperationWithBlock:^{
for (int i = 0; i <= 100; i++) {
NSLog(@"------這是duo線程1----%d",i);
}
}];
//第五種建立方式
NSOperationQueue *operationQueue = [[NSOperationQueue alloc]init];
//設定線程進行的並發數
operationQueue.maxConcurrentOperationCount = 5;
NSInvocationOperation * invocationQperation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(mutableThread:) object:nil];
//將線程添加到線程隊列中
[operationQueue addOperation: invocationQperation];
備忘:
1、假設主進程裡面有3個線程,分別是1、2、3,如何先讓線程2先執行呢?
在多線程中,各線程之間,可以根據線程之間的優先順序來進行設定。
共有五個優先順序:
NSOperationQueuePriorityVeryLow = -8L;
NSOperationQueuePriorityLow = -4L;
NSOperationQueuePriorityNormal = 0;
NSOperationQueuePriorityHigh = 4;
NSOperationQueuePriorityVeryHigh = 8
2、UI的操作都是在主線程上啟動並執行。那如何從其他線程跳轉到主線程呢?
通過設計的方法來進行線程之間的跳轉:
[self performSelectorOnMainThread:@selector(mainThread) withObject:self waitUntilDone:YES];
3、NSThread的常用方法
//擷取當前線程對象
+ (NSThread *)currentThread;
//判斷當前線程是否是多線程
+ (BOOL)isMultiThreaded;
//是當前線程睡眠指定的時間,單位為秒
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;
//退出當前線程
+ (void)exit;
//判斷當前線程是否為主線程
+ (BOOL)isMainThread;
//啟動該線程
- (void)start
小編希望和各位大牛一起探討,並希望大牛指正!!!!!
網路與多線程---OC中多線程使用方法(一)