Create multiple threads in Objecttive-C

Source: Internet
Author: User

Create multiple threads in Objecttive-C

There are two methods to create multithreading in Objecttive-C: initWithTarget and detachNewThreadSelector.

The following two instances are used to create multi-threaded instances and support passing parameters.

 

InitWithTarget Method

 

////  main.m//  initWithTarget//  Created by exchen on 5/8/15.//  Copyright (c) 2015 exchen. All rights reserved.//#import 
 
  @interface classa : NSObject-(void)StartThread:(NSString *)str;@end@implementation classa-(void)StartThread:(NSString *)str{     sleep(3);        NSLog(str);       exit(0);}@endint main(int argc, const char * argv[]) {    @autoreleasepool {        // insert code here...        NSLog(@"Hello, World!");    }        classa *a = [[classa alloc] init];    NSThread *thread = [[NSThread alloc] initWithTarget:a selector:@selector(StartThread:) object:@"Start"];    [thread start];        sleep(5);    return 0;}
 

DetachNewThreadSelector Mode

 

////  main.m//  TestThread////  Created by exchen on 5/8/15.//  Copyright (c) 2015 exchen. All rights reserved.//#import 
 
  @interface classa : NSObject-(void)StartThread:(NSString *)str;@end@implementation classa-(void)StartThread:(NSString *)str{    NSLog(@"%@",str);    exit(0);}@endint main(int argc, const char * argv[]) {    @autoreleasepool {        // insert code here...        NSLog(@"Hello, World!");                classa *a = [[classa alloc] init];                [NSThread detachNewThreadSelector:@selector(StartThread:) toTarget:a withObject:@"Start"];                sleep(5);            }    return 0;}
 


 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.