Locks, Atomic ו-ConcurrentHashMapLocks, Atomic & ConcurrentHashMap
ReentrantLock ו-ReadWriteLock, AtomicInteger ו-compareAndSet, ו-ConcurrentHashMap.
ReentrantLock and ReadWriteLock, AtomicInteger and compareAndSet, and ConcurrentHashMap.
מונה ביקורים אטומיAn atomic visit counter
תזכורת: מה ביקשוReminder: the task
static final AtomicInteger hits. ארבעה threads, כל אחד 25,000 incrementAndGet(). הדפיסו hits 100000.
static final AtomicInteger hits. Four threads, each 25,000 incrementAndGet(). Print hits 100000.
סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs
כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.
With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.
AtomicInteger.incrementAndGetAtomicInteger.incrementAndGet
הפתרון המלא והפלט שלוFull solution and its output
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
static final AtomicInteger hits = new AtomicInteger();
public static void main(String[] args) throws InterruptedException {
Runnable job = () -> {
for (int i = 0; i < 25000; i++) {
hits.incrementAndGet();
}
};
Thread[] ts = new Thread[4];
for (int k = 0; k < ts.length; k++) {
ts[k] = new Thread(job);
ts[k].start();
}
for (Thread t : ts) {
t.join();
}
System.out.println("hits " + hits.get());
}
}hits 100000
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מלאי עם ReentrantLockStock with a ReentrantLock
תזכורת: מה ביקשוReminder: the task
מלאי 5000. שלושה threads מורידים כל אחד 1000 פעמים, כל הורדה בתוך lock.lock() ו-try/finally. הדפיסו stock 2000.
A stock of 5000. Three threads each decrement 1000 times, each decrement inside lock.lock() and try/finally. Print stock 2000.
סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs
כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.
With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.
count++ בתוך synchronizedcount++ inside synchronized
הפתרון המלא והפלט שלוFull solution and its output
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Main {
static final Lock lock = new ReentrantLock();
static int stock = 5000;
public static void main(String[] args) throws InterruptedException {
Runnable job = () -> {
for (int i = 0; i < 1000; i++) {
lock.lock();
try {
stock--;
} finally {
lock.unlock();
}
}
};
Thread[] ts = new Thread[3];
for (int k = 0; k < ts.length; k++) {
ts[k] = new Thread(job);
ts[k].start();
}
for (Thread t : ts) {
t.join();
}
System.out.println("stock " + stock);
}
}stock 2000
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
צייד באגים: get ואז putBug hunter: get then put
תזכורת: מה ביקשוReminder: the task
המפה היא ConcurrentHashMap, ובכל זאת הספירה יוצאת נמוכה מדי, ולא תמיד אותו דבר. החליפו את put(get + 1) ב-merge כך שתמיד יודפס {Dune=2000, Emma=2000}.
The map is a ConcurrentHashMap, and still the count comes out too low, and not always the same. Replace put(get + 1) with merge so it always prints {Dune=2000, Emma=2000}.
סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs
כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.
With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.
count++ בלי הגנה: נסו לאבד עדכוןcount++ unprotected: try to lose an update
AtomicInteger.incrementAndGetAtomicInteger.incrementAndGet
הפתרון המלא והפלט שלוFull solution and its output
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
public class Main {
static final Map<String, Integer> loans = new ConcurrentHashMap<>();
public static void main(String[] args) throws InterruptedException {
Runnable job = () -> {
for (int i = 0; i < 1000; i++) {
String key = i % 2 == 0 ? "Dune" : "Emma";
loans.merge(key, 1, Integer::sum);
}
};
Thread[] ts = new Thread[4];
for (int k = 0; k < ts.length; k++) {
ts[k] = new Thread(job);
ts[k].start();
}
for (Thread t : ts) {
t.join();
}
System.out.println(new TreeMap<>(loans));
}
}{Dune=2000, Emma=2000}יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
שיא עם compareAndSetA record with compareAndSet
תזכורת: מה ביקשוReminder: the task
שלושה threads מציעים ציונים. offer(score) מעדכנת את best רק אם הציון גבוה יותר, בלולאת compareAndSet (בלי מנעול). הדפיסו best 99.
Three threads offer scores. offer(score) updates best only if the score is higher, in a compareAndSet loop (no lock). Print best 99.
סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs
כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.
With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.
AtomicInteger.incrementAndGetAtomicInteger.incrementAndGet
הפתרון המלא והפלט שלוFull solution and its output
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
static final AtomicInteger best = new AtomicInteger(0);
static void offer(int score) {
int cur;
do {
cur = best.get();
if (score <= cur) {
return;
}
} while (!best.compareAndSet(cur, score));
}
public static void main(String[] args) throws InterruptedException {
int[][] scores = {{12, 88, 40}, {95, 3, 61}, {70, 99, 15}};
Thread[] ts = new Thread[scores.length];
for (int k = 0; k < ts.length; k++) {
int[] mine = scores[k];
ts[k] = new Thread(() -> {
for (int s : mine) {
offer(s);
}
});
ts[k].start();
}
for (Thread t : ts) {
t.join();
}
System.out.println("best " + best.get());
}
}best 99
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מדף, צעד 36: מטמון בטוח לפרטי ספריםShelf, step 36: a thread-safe book cache
תזכורת: מה ביקשוReminder: the task
BookCache.details(title) משתמשת ב-computeIfAbsent של ConcurrentHashMap: הטעינה (שמגדילה loads) רצה פעם אחת לכל כותר, גם כששני threads מבקשים יחד. הדפיסו Dune (4 letters) | loaded 3 times.
BookCache.details(title) uses ConcurrentHashMap's computeIfAbsent: the load (which bumps loads) runs once per title, even when two threads ask together. Print Dune (4 letters) | loaded 3 times.
סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs
כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.
With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.
AtomicInteger.incrementAndGetAtomicInteger.incrementAndGet
הפתרון המלא והפלט שלוFull solution and its output
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
public static void main(String[] args) throws InterruptedException {
BookCache cache = new BookCache();
Runnable reader = () -> {
for (String t : new String[]{"Dune", "Emma", "Dune", "Ulysses", "Emma", "Dune"}) {
cache.details(t);
}
};
Thread a = new Thread(reader);
Thread b = new Thread(reader);
a.start();
b.start();
a.join();
b.join();
System.out.println(cache.details("Dune") + " | loaded " + cache.loads() + " times");
}
}
class BookCache {
private final Map<String, String> cache = new ConcurrentHashMap<>();
private final AtomicInteger loads = new AtomicInteger();
String details(String title) {
return cache.computeIfAbsent(title, t -> {
loads.incrementAndGet();
return t + " (" + t.length() + " letters)";
});
}
int loads() {
return loads.get();
}
}Dune (4 letters) | loaded 3 times
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
ReadWriteLockReadWriteLock
תזכורת: מה ביקשוReminder: the task
Catalog עם ReentrantReadWriteLock: add עם מנעול הכתיבה, size עם מנעול הקריאה. כותב מוסיף 3 ספרים וקורא קורא במקביל. הדפיסו 3 books.
Catalog with a ReentrantReadWriteLock: add with the write lock, size with the read lock. A writer adds 3 books while a reader reads. Print 3 books.
סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs
כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.
With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.
count++ בתוך synchronizedcount++ inside synchronized
הפתרון המלא והפלט שלוFull solution and its output
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class Main {
public static void main(String[] args) throws InterruptedException {
Catalog c = new Catalog();
Thread writer = new Thread(() -> {
for (int i = 1; i <= 3; i++) {
c.add("Book " + i);
}
});
Thread reader = new Thread(() -> {
for (int i = 0; i < 3; i++) {
c.size();
}
});
writer.start();
reader.start();
writer.join();
reader.join();
System.out.println(c.size() + " books");
}
}
class Catalog {
private final List<String> books = new ArrayList<>();
private final ReadWriteLock rw = new ReentrantReadWriteLock();
void add(String b) {
rw.writeLock().lock();
try {
books.add(b);
} finally {
rw.writeLock().unlock();
}
}
int size() {
rw.readLock().lock();
try {
return books.size();
} finally {
rw.readLock().unlock();
}
}
}3 books
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
tryLock עם זמן קצובtryLock with a timeout
תזכורת: מה ביקשוReminder: the task
main מחזיק את מנעול המדפסת. thread אחר מנסה tryLock(100, MILLISECONDS), מוותר, ומדפיס printer busy, try later. main משחרר ומדפיס held by main: false.
main holds the printer lock. Another thread tries tryLock(100, MILLISECONDS), gives up, and prints printer busy, try later. main releases and prints held by main: false.
סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs
כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.
With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.
אותו סדר מנעולים: אין deadlockThe same lock order: no deadlock
הפתרון המלא והפלט שלוFull solution and its output
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
public class Main {
public static void main(String[] args) throws InterruptedException {
ReentrantLock printer = new ReentrantLock();
printer.lock();
Thread other = new Thread(() -> {
try {
if (printer.tryLock(100, TimeUnit.MILLISECONDS)) {
printer.unlock();
System.out.println("printed");
} else {
System.out.println("printer busy, try later");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
other.start();
other.join();
printer.unlock();
System.out.println("held by main: " + printer.isHeldByCurrentThread());
}
}printer busy, try later held by main: false
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.