NSThread関連

5857 ワード

参考:http://blog.csdn.net/linzhiji/article/details/6848652
--------------
1.経典のticket thread
注:@synchronized()とスレッドロックの関係
//
//  TicketSeller.h
//  UpperTestView
//
//  Created by fengshaobo on 12-9-24.
//  Copyright (c) 2012  Maxthon. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface TicketSeller : NSObject
{
    int tickets;
    int count;
}

@property (nonatomic, retain) NSThread* ticketsThreadone;
@property (nonatomic, retain) NSThread* ticketsThreadtwo;
@property (nonatomic, retain) NSCondition* ticketsCondition;

- (void)startTicketThread;

@end
m.
//
//  TicketSeller.m
//  UpperTestView
//
//  Created by fengshaobo on 12-9-24.
//  Copyright (c) 2012  Maxthon. All rights reserved.
//

#import "TicketSeller.h"

#define SYNCHRONIZED 1

@implementation TicketSeller
@synthesize ticketsCondition, ticketsThreadone, ticketsThreadtwo;

- (id)init
{
    self = [super init];
    if(self){
        
    }
    return self;
}

- (void)dealloc
{
    [ticketsThreadone release];
    [ticketsThreadtwo release];
    [ticketsCondition release];
    [super dealloc];
}

- (void)startTicketThread
{
    tickets = 100;
    count = 0;
    
    //    
    NSCondition *tmpCondition = [[NSCondition alloc] init];
    self.ticketsCondition = tmpCondition;
    [tmpCondition release];
    
    NSThread *threadOne = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
    [threadOne setName:@"Thread-1"];
    self.ticketsThreadone = threadOne;
    [threadOne release];
    [self.ticketsThreadone start];
    
    NSThread *threadTwo = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
    [threadTwo setName:@"Thread-2"];
    self.ticketsThreadtwo = threadTwo;
    [threadTwo release];
    [self.ticketsThreadtwo start];
}





/* --------------------------------------------------
 1.   :
 2012-09-24 16:18:32.220 UpperTestView[3455:3c03]      :100,  :0,   :Thread-2
 2012-09-24 16:18:32.220 UpperTestView[3455:3703]      :100,  :0,   :Thread-1
 2012-09-24 16:18:32.722 UpperTestView[3455:3703]      :98,  :2,   :Thread-1
 2012-09-24 16:18:32.722 UpperTestView[3455:3c03]      :98,  :2,   :Thread-2
 2012-09-24 16:18:33.224 UpperTestView[3455:3c03]      :96,  :4,   :Thread-2
 2012-09-24 16:18:33.224 UpperTestView[3455:3703]      :96,  :4,   :Thread-1
 
 2.@synchronized /     :
 2012-09-24 16:19:46.598 UpperTestView[3484:3703]      :100,  :0,   :Thread-1
 2012-09-24 16:19:47.100 UpperTestView[3484:3c03]      :99,  :1,   :Thread-2
 2012-09-24 16:19:47.602 UpperTestView[3484:3703]      :98,  :2,   :Thread-1
 2012-09-24 16:19:48.103 UpperTestView[3484:3c03]      :97,  :3,   :Thread-2
 2012-09-24 16:19:48.604 UpperTestView[3484:3703]      :96,  :4,   :Thread-1
 2012-09-24 16:19:49.106 UpperTestView[3484:3c03]      :95,  :5,   :Thread-2
 -------------------------------------------------- */
- (void)run{
    while (TRUE) {
        
#if SYNCHRONIZED
        
        //   -:@synchronized
        @synchronized(self){
            if(tickets > 0){
                [NSThread sleepForTimeInterval:0.5];
                count = 100 - tickets;
                NSLog(@"     :%d,  :%d,   :%@",tickets,count,[[NSThread currentThread] name]);
                tickets--;
            }else{
                break;
            }
        }
        
        /* --------------------------------------------------
         note:
         @synchronized(self)
                    self      
         
         The @synchronized directive is a convenient way to create mutex locks on the fly in Objective-C code. The @synchronized directive does what any other mutex lock would do—it prevents different threads from acquiring the same lock at the same time. In this case, however, you do not have to create the mutex or lock object directly. Instead, you simply use any Objective-C object as a lock token, as shown in the following example:
         
         - (void)myMethod:(id)anObj
         {
             @synchronized(anObj)
             {
                // Everything between the braces is protected by the @synchronized directive.
             }
         }
         
         The object passed to the @synchronized directive is a unique identifier used to distinguish the protected block. If you execute the preceding method in two different threads, passing a different object for the anObj parameter on each thread, each would take its lock and continue processing without being blocked by the other. If you pass the same object in both cases, however, one of the threads would acquire the lock first and the other would block until the first thread completed the critical section.
         
         As a precautionary measure, the @synchronized block implicitly adds an exception handler to the protected code. This handler automatically releases the mutex in the event that an exception is thrown. This means that in order to use the @synchronized directive, you must also enable Objective-C exception handling in your code. If you do not want the additional overhead caused by the implicit exception handler, you should consider using the lock classes.
         -------------------------------------------------- */
#else 
        
        //    :  
        [ticketsCondition lock];
        if(tickets > 0){
            [NSThread sleepForTimeInterval:0.5];
            count = 100 - tickets;
            NSLog(@"     :%d,  :%d,   :%@",tickets,count,[[NSThread currentThread] name]);
            tickets--;
        }else{
            break;
        }
        [ticketsCondition unlock];
        
#endif

    }
}

@end


2.まだ続きがありません。よく検討してください。
NSOperation Que、追加
3.問題:
  -》スレッドstart以降、どのようにキャンセルして、cancleを試しても、exitは使えなくて、ずっと運行しています。最初から止められないようです。