נבנה על ידיBuilt by Ariel Yohimovich

JavaJava

מבחן 6: מקביליות ו-ThreadsExam 6: Concurrency and threads

Threads, race conditions, synchronized, Atomic, ExecutorService, BlockingQueue ו-deadlock

Threads, race conditions, synchronized, atomics, ExecutorService, BlockingQueue and deadlock

90 דקותminutes4 שאלות בחירהmultiple choice3 שאלות קודcoding questions100 נקודותpoints
90:00השעון רק עוזר להתאמן. אפשר גם בלי.The timer is just for practice. You can skip it.

חלק א: שאלות בחירה (5 נקודות לשאלה)Part A: multiple choice (5 points each)

התשובות מתגלות רק כשמסיימים את המבחן.Answers are revealed only when you finish the exam.

1. מה יודפס?What is printed? 5
java
Thread t = new Thread(() -> System.out.println(Thread.currentThread().getName()));
t.run();
2. שני threads מריצים count++ אלף פעמים כל אחד על int משותף בלי סנכרון. מה התוצאה?Two threads each run count++ a thousand times on a shared int without synchronization. What's the result? 5
3. מה יודפס?What is printed? 5
java
AtomicInteger c = new AtomicInteger();
Runnable r = () -> {
    for (int i = 0; i < 1000; i++) {
        c.incrementAndGet();
    }
};
Thread a = new Thread(r);
Thread b = new Thread(r);
a.start();
b.start();
a.join();
b.join();
System.out.println(c.get());
4. T1 נועל A ואז B. T2 נועל B ואז A. מה יכול לקרות?T1 locks A then B. T2 locks B then A. What can happen? 5

חלק ב: שאלות קודPart B: coding questions

שאלהQuestion 5

מונה מסונכרןA synchronized counter

כתבו class SafeCounter עם synchronized void increment() ו-synchronized int get(). ב-main ארבעה threads מגדילים אלף פעמים כל אחד, join לכולם, ומדפיסים 4000. בלי Atomic.

Write class SafeCounter with synchronized void increment() and synchronized int get(). In main four threads increment a thousand times each, join all of them, and print 4000. No atomics.

איך הפלט אמור להיראות?What should the output look like?
4000
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: synchronized על מתודה נועל את העצם this.synchronized on a method locks the object this.
הפתרון שלנוOur solution
Main.java
public class Main {
    public static void main(String[] args) throws InterruptedException {
        SafeCounter c = new SafeCounter();
        Thread[] ts = new Thread[4];
        for (int i = 0; i < ts.length; i++) {
            ts[i] = new Thread(() -> {
                for (int k = 0; k < 1000; k++) {
                    c.increment();
                }
            });
            ts[i].start();
        }
        for (Thread t : ts) {
            t.join();
        }
        System.out.println(c.get());
    }
}

class SafeCounter {
    private int count;

    synchronized void increment() {
        count++;
    }

    synchronized int get() {
        return count;
    }
}
פלטOutput
4000

יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.

מחווןRubric (25 נקודותpoints)

כשכל הבדיקות עוברות, כל השורות מסומנות. אם לא, סמנו בעצמכם מה כן עשיתם נכון.When every check passes, all rows are ticked. If not, tick what you did get right.

שאלהQuestion 6

ספירת מילים במקבילCounting words in parallel

כתבו static int countWords(List<String> docs): כל מסמך נספר במשימה משלו ב-ExecutorService של 4 threads (Callable<Integer>), והתוצאות מחוברות מה-Future. מילה היא רצף בלי רווחים. main מדפיס 7.

Write static int countWords(List<String> docs): each document is counted in its own task in an ExecutorService of 4 threads (Callable<Integer>), and the results are added up from the Futures. A word is a run without spaces. main prints 7.

איך הפלט אמור להיראות?What should the output look like?
7
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: doc.isBlank() ? 0 : doc.trim().split("\\s+").length.doc.isBlank() ? 0 : doc.trim().split("\\s+").length.
רמזHint 2: shutdown() ב-finally.shutdown() in a finally.
הפתרון שלנוOur solution
Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Main {
    static int countWords(List<String> docs) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(4);
        try {
            List<Future<Integer>> parts = new ArrayList<>();
            for (String doc : docs) {
                parts.add(pool.submit(() -> doc.isBlank() ? 0 : doc.trim().split("\\s+").length));
            }
            int total = 0;
            for (Future<Integer> f : parts) {
                total += f.get();
            }
            return total;
        } finally {
            pool.shutdown();
        }
    }

    public static void main(String[] args) throws Exception {
        System.out.println(countWords(List.of("the night train", "  ", "stops at  every station")));
    }
}
פלטOutput
7

יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.

מחווןRubric (25 נקודותpoints)

כשכל הבדיקות עוברות, כל השורות מסומנות. אם לא, סמנו בעצמכם מה כן עשיתם נכון.When every check passes, all rows are ticked. If not, tick what you did get right.

שאלהQuestion 7

פס ייצורA pipeline

כתבו static int pipeline(int n): thread יצרן מכניס 1 עד n ל-ArrayBlockingQueue בגודל 2, ואחריהם -1 ("גלולת רעל" שאומרת שנגמר). thread צרכן מוציא ומחבר עד שהוא מקבל -1. המתודה מחכה לשניהם ומחזירה את הסכום. main מדפיס 15.

Write static int pipeline(int n): a producer thread puts 1 to n into an ArrayBlockingQueue of size 2, followed by -1 (a "poison pill" saying it's over). A consumer thread takes and adds until it gets -1. The method waits for both and returns the sum. main prints 15.

איך הפלט אמור להיראות?What should the output look like?
15
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: put נחסם כשהתור מלא, take כשהוא ריק.put blocks when the queue is full, take when it's empty.
רמזHint 2: את הסכום מחזיקים ב-AtomicInteger או במערך של איבר אחד, כי lambda לא יכולה לשנות משתנה מקומי.Keep the sum in an AtomicInteger or a one-item array, because a lambda can't change a local variable.
הפתרון שלנוOur solution
Main.java
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    static int pipeline(int n) throws InterruptedException {
        BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(2);
        AtomicInteger sum = new AtomicInteger();
        Thread producer = new Thread(() -> {
            try {
                for (int i = 1; i <= n; i++) {
                    queue.put(i);
                }
                queue.put(-1);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        Thread consumer = new Thread(() -> {
            try {
                while (true) {
                    int x = queue.take();
                    if (x == -1) {
                        break;
                    }
                    sum.addAndGet(x);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        producer.start();
        consumer.start();
        producer.join();
        consumer.join();
        return sum.get();
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println(pipeline(5));
    }
}
פלטOutput
15

יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.

מחווןRubric (30 נקודותpoints)

כשכל הבדיקות עוברות, כל השורות מסומנות. אם לא, סמנו בעצמכם מה כן עשיתם נכון.When every check passes, all rows are ticked. If not, tick what you did get right.

נבנה על ידיBuilt by Ariel Yohimovich