Skip to content

Instantly share code, notes, and snippets.

@evanlong
Created August 31, 2011 05:48
Show Gist options
  • Save evanlong/1182898 to your computer and use it in GitHub Desktop.
Save evanlong/1182898 to your computer and use it in GitHub Desktop.
class MyClass1 {
private int _fastCounter = 0;
private int _slowCounter = 0;
public synchronized void methodSlow() {
System.out.println("slowCounter.start " + _slowCounter);
try {
Thread.sleep(5*1000);
}
catch(Exception e) {
}
System.out.println("slowCounter.done " + _slowCounter);
_slowCounter++;
}
public void methodFast() {
System.out.println("fastCounter " + _fastCounter);
try {
Thread.sleep(1000);
}
catch(Exception e) {
}
_fastCounter++;
}
}
public class Main {
public static void main(String[] args) {
final MyClass1 c1 = new MyClass1();
Thread t1 = new Thread(new Runnable() {
public void run() {
while(true) {
c1.methodSlow();
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
while(true) {
c1.methodFast();
}
}
});
t1.start();
t2.start();
}
}
#import <Foundation/Foundation.h>
@interface MyClass1 : NSObject {
int _slowCounter;
int _fastCounter;
}
- (void)methodSlow;
- (void)methodFast;
@end
@implementation MyClass1
- (void)methodSlow {
@synchronized(self) {
NSLog(@"slowCounter.start = %d", _slowCounter);
sleep(5);
NSLog(@"slowCounter.done = %d", _slowCounter);
_slowCounter++;
}
}
- (void)methodFast {
// this can still run and be called even if someone has the lock on self in methodSlow
NSLog(@"fastCounter = %d", _fastCounter);
sleep(1);
_fastCounter++;
}
@end
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
dispatch_queue_t q1 = dispatch_queue_create("example.queue1", NULL);
dispatch_queue_t q2 = dispatch_queue_create("example.queue2", NULL);
MyClass1 *c1 = [[MyClass1 alloc] init];
dispatch_async(q1, ^{
while (true) {
[c1 methodFast];
}
});
dispatch_async(q2, ^{
while (true) {
[c1 methodSlow];
}
});
while (true) {
sleep(10);
}
[pool drain];
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment