More Related Content
Similar to ぐだ生 Java入門第ニ回(synchronized and lock)
Similar to ぐだ生 Java入門第ニ回(synchronized and lock) (20)
More from Makoto Yamazaki
More from Makoto Yamazaki (13)
ぐだ生 Java入門第ニ回(synchronized and lock)
- 2. Who am I
• YAMAZAKI Makoto(twitter: @zaki50)
• Android
•
• StickyShortcut
• Java
- 7. synchronized
class Sample {
public synchronized void execute1() {
//
}
public void execute1b() {
synchronized (this) {
//
}
}
public static synchronized void execute2() {
//
}
public static synchronized void execute2b() {
synchronized (Sample.class) {
//
}
}
}
- 11. •
(by Wikipedia)
• Java 1
1
1
1
- 12. •
• synchronized
• Object#wait()
•
• synchronized
• Object#wait()
- 14. synchronized
class Sample {
public synchronized void execute1() {
//
}
public void execute1b() {
synchronized (this) {
//
}
}
public static synchronized void execute2() {
//
}
public static synchronized void execute2b() {
synchronized (Sample.class) {
//
}
}
}
- 18. private static boolean stopRequested = false;
private static int value = 0;
public static void main(String[] args) throws Exception {
new Thread() {
@Override
public void run() {
int i = 0;
if (!stopRequested) {
while (!stopRequested) { while (true) {
i++; i++;
}
}
}
System.out.println(value);
}
}.start();
TimeUnit.SECONDS.sleep(1L);
value = 100;
stopRequested = true;
}
- 19. private static boolean stopRequested = false;
private static int value = 0;
public static void main(String[] args) throws Exception {
new Thread() {
@Override
public void run() {
int i = 0;
while (!stopped()) {
i++;
}
System.out.println(value);
}
}.start(); private synchronized static void stop() {
stopRequested = true;
TimeUnit.SECONDS.sleep(1L); }
value = 100;
stop(); private synchronized static boolean stopped() {
} return stopRequested;
}
- 22. volatile
private volatile static boolean stopRequested = false;
private volatile static int value = 0;
public static void main(String[] args) throws Exception {
new Thread() {
@Override
public void run() {
int i = 0;
while (!stopRequested) {
i++;
}
System.out.println(value);
}
}.start();
TimeUnit.SECONDS.sleep(1L);
value = 100;
stopRequested = true;
}
- 24. Lock
• synchronized
• lock() // synchronized
• tryLock() //
• tryLock(long,TimeUnit) //
• lockInterruptibly() //
- 25. •
• try - finally
Lock l = ...;
l.lock();
try {
//
} finally {
l.unlock();
}
- 26. ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
Lock wl = rwLock.writeLock();
Lock rl;
wl.lock();
try {
// write
rl = rwLock.readLock();
} finally {
wl.unlock();
}
try {
// read
} finally {
rl.unlock();
}
Editor's Notes
- \n
- \n
- \n
- \n
- \n
- \n
- \n
- \n
- \n
- \n
- \n
- \n
- \n
- \n
- \n
- \n
- \n
- \n
- \n
- \n
- \n
- \n
- \n
- \n
- \n
- \n
- \n
- \n
- \n
- \n
- \n