首页 > 代码库 > Swift 学习-多线程
Swift 学习-多线程
1:第一种多线程
func fun1(){
for i in 200...300{
NSLog("%d",i);
}
}
func fun2(){
for i in 300...400{
NSLog("%d",i);
}
}
var th1 = NSThread(target:self,selector:"fun1",object:nil);
th1.start();
//开启线程
NSThread.detachNewThreadSelector("fun2",toTarget:self,withObject:nil);
第二种创建线程池:
var queue = NSOperationQueue();
queue.maxConcurrentOperationCount = 1;
queue.addOperationWithBlock({
for i in 400...500{
NSLog("%d",i);
}
var op = NSInvocationOperation (target:self,selector:"fun1",object:nil);
var op1 = NSInvocationOperation(target:self,selector:"fun2",object:nil);
queue.addOperation(op);
queue.addOperation(op1);
})
第三种GCD创建多线程
var queue = dispatch_queue_create("test", nil);
dispatch_async(queue, {
for i in 0...100{
NSLog("异常%d", i);
}
dispatch_sync(dispatch_get_main_queue(), {
NSLog("是否是主线程\(NSThread.isMainThread())");
})
})