myThread

//

//  myThread.h

//  myTask

//

//  Created by user on 12-4-9.

//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.

//


#import <Foundation/Foundation.h>


@interface myThread : NSObject{

    int a;

    NSLock *lock;

    NSDictionary *dicData;

    

    int tickets;

    int count;

    NSThread* ticketsThreadone;

    NSThread* ticketsThreadtwo;

    NSCondition* ticketsCondition;

}


-(void) doSomeThing;


-(myThread * ) myInit;

-(void)aMethodFun;

+(void)aMethod:(void *)paraSelf;


-(void)writeFile:(NSString *)file;


-(NSString *)readFile;


-(void) text;


-(void) readText;


-(void) rwFile;


-(void) wDouble;


-(void) openfile;

@end


//

//  myThread.m

//  myTask

//

//  Created by user on 12-4-9.

//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.

//


#import "myThread.h"


@implementation myThread


-(myThread * ) myInit{      

    self = [super init];      

    if(self)   {    

        tickets = 100;

        count = 0;

        // 锁对象

        ticketsCondition = [[NSCondition alloc] init];

        ticketsThreadone = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];

        [ticketsThreadone setName:@"Thread-1"];

        [ticketsThreadone start];  

        

        

        ticketsThreadtwo = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];

        [ticketsThreadtwo setName:@"Thread-2"];

        [ticketsThreadtwo start];

        //[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];

        // Override point for customization after application launch

        

        lock = [[NSLock alloc] init];

        NSString *fileName = [self readFile];

        NSLog(@"%@", fileName);

        [self openfile];

        [self wDouble];

        [self rwFile];

        [self readText];

        [self writeFile:fileName];

        [self  doSomeThing];  

        [self text];

        for(int x=0;x<50;++x)

        {

            [lock lock];

            printf("Main thread says x is %i\n",x);

            sleep(1);

            printf("Main thread lets go %i\n",x);

            [lock unlock];

            sleep(1);

        }


    }       

    return self;   

}

-(void) doSomeThing{

    [NSThread detachNewThreadSelector:@selector(aMethod:) toTarget:[myThread class] withObject:self];

    

        return ;

}


-(void)aMethodFun

{

    a = 10;

    int x = 10;

}

+(void)aMethod:(void *)paraSelf{

    //a = 10;

    myThread *pMyThread = (myThread *)paraSelf;

    [pMyThread aMethodFun];

    

    int x;

    for(x=0;x<50;++x)

    {

        printf("Object Thread says x is %i\n",x);

        usleep(1);

    }

}


-(void)writeFile:(NSString *)file 

    //创建文件管理器 

    NSFileManager *fileManager = [NSFileManager defaultManager]; 

    //获取路径 

    //参数NSDocumentDirectory要获取那种路径 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

    NSString *documentsDirectory = [paths objectAtIndex:0];//去处需要的路径    

    //更改到待操作的目录下 

    [fileManager changeCurrentDirectoryPath:[documentsDirectory stringByExpandingTildeInPath]]; 

    //创建文件fileName文件名称,contents文件的内容,如果开始没有内容可以设置为nilattributes文件的属性,初始为nil 

    //获取文件路径 

    [fileManager removeItemAtPath:@"data2" error:nil]; 

    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data2"]; 

    //创建数据缓冲 

    NSMutableData *writer = [[NSMutableData alloc] init]; 

    //将字符串添加到缓冲中 

    [writer appendData:[file dataUsingEncoding:NSUTF8StringEncoding]]; 

    //将其他数据添加到缓冲中 

    //将缓冲的数据写入到文件中 

    [writer writeToFile:path atomically:YES]; 

    [writer release]; 


-(NSString *)readFile 

    NSString *string1 = [[NSString alloc] initWithContentsOfFile: @"/text/1.txt"];

    

    NSLog(@"%@" ,string1);

    

    //创建文件管理器 

    NSFileManager *fileManager = [NSFileManager defaultManager]; 

    //获取路径 

    //参数NSDocumentDirectory要获取那种路径 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

    NSString *documentsDirectory = [paths objectAtIndex:0];//去处需要的路径    

    //更改到待操作的目录下 

    [fileManager changeCurrentDirectoryPath:[documentsDirectory stringByExpandingTildeInPath]]; 

    //获取文件路径 

    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data"]; 

    NSData *reader = [NSData dataWithContentsOfFile:path]; 

    return [[NSString alloc] initWithData:reader 

                                 encoding:NSUTF8StringEncoding]; 


-(void) text

{

    NSFileManager *fm;  

    NSString *fName = @"path.m";  

    NSString *path,*tempdir,*extension,*homedir,*fullpath;  

    NSString *upath = @"~stevekochan/progs/../ch16/./path.m";  

    NSArray *components;  

    

    

    fm = [NSFileManager defaultManager];  

    

    //当前工作目录

    NSString *resourcePath=[[NSBundle mainBundle] resourcePath];

    NSLog(@"current work directiry : %@", resourcePath);

    

    //Get the temporary working directory  

    

    tempdir = NSTemporaryDirectory();  

    NSLog(@"Temporary Directory is %@",tempdir);  

    

    //Extract the base directory from current directory  

    path  = [fm currentDirectoryPath];  

    NSLog(@"Base dir is %@",[path lastPathComponent]);  

    

    //Create a full path to the file fName in current directory  

    fullpath = [path stringByAppendingPathComponent:fName];  

    NSLog(@"fullpath to %@ is %@",fName,fullpath);  

    

    //Get the file name extension  

    extension = [fullpath pathExtension];  

    NSLog(@"extension for %@ is %@", fullpath,extension);  

    

    //Get user's home directory  

    homedir = NSHomeDirectory();  

    NSLog(@"Your home directory is %@",homedir);  

    

    //Divide a path into its components  

    components = [homedir pathComponents];  

    

    for(int i = 0; i < [components count]; i++)  

    {  

        NSLog(@"%@",[components objectAtIndex: i]);  

    }  

    

    //"Standardize" a path  

    NSLog(@"%@ => %@",upath,[upath stringByStandardizingPath]);  

    

}


-(void) readText

{

    NSFileManager *fm=[NSFileManager defaultManager];

    NSString *file1=@"/text/1.txt";

    NSString *file2=@"/text/2.txt";

    

    

    NSData *data=[fm contentsAtPath:file2];

    //读取文件内容

    if(![fm fileExistsAtPath:file1])

    {

        [fm createFileAtPath:file1 contents:data attributes:nil];

        //如果文件不存在,就以file2的文件内容创建file1

    }

    NSString *myData = [NSString stringWithContentsOfFile:file1 encoding:NSUTF8StringEncoding error:nil];

    NSLog(@"%@",myData);

    

    //创建数据缓冲 

    NSMutableData *writer = [[NSMutableData alloc] init]; 

    //将字符串添加到缓冲中 

    [writer appendData:[myData dataUsingEncoding:NSUTF8StringEncoding]]; 

    //将其他数据添加到缓冲中 

    //将缓冲的数据写入到文件中 

    [writer writeToFile:file2 atomically:YES]; 

    [writer release]; 


}


-(void) rwFile

{

    NSString *file1=@"/text/1.txt";

    NSString *file2=@"/text/2.txt";

    NSData *myData = [[[NSData alloc] initWithContentsOfFile:file1] autorelease];

    

    [myData writeToFile:file2 atomically:YES];

}


-(void) wDouble

{

    NSString *file1=@"/text/3.txt";

    double *MHB = (double *)malloc(2 * sizeof(double));

    MHB[0] = 0.0;

    MHB[1] = 1.0;

    NSString *myData = [[NSString alloc] initWithString: @"data : "];

    

    myData = [myData stringByAppendingFormat:@"%lf %lf",MHB[0], MHB[1]];

    

    //创建数据缓冲 

    NSMutableData *writer = [[NSMutableData alloc] init]; 

    //将字符串添加到缓冲中 

    [writer appendData:[myData dataUsingEncoding:NSUTF8StringEncoding]]; 

    //将其他数据添加到缓冲中 

    //将缓冲的数据写入到文件中 

    [writer writeToFile:file1 atomically:YES]; 

    [writer release]; 


}


-(void) openfile

{

    FILE *fp = NULL;

    fp = fopen("/text/5.txt", "w");

    

    if(fp == NULL)

        NSLog(@"failed to open file");

    

    fprintf(fp, "%d", 1);

    

    fclose(fp);

}


- (void)run{

    while (TRUE) {

        // 上锁

        [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];

    }

}

@end


你可能感兴趣的:(myThread)