Threads
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
A thread of execution is an independent "line" of code inside a program. Several threads run at the same time — on different processor cores.
Thread t = new Thread(() -> System.out.println("working in a thread"));
t.start(); // start it (not run()! run() would execute in the current thread)
t.join(); // wait for it to finish
A data race. Two threads do count++ on a shared variable — that's three steps (read, add,
write), and the steps of different threads get interleaved: some of the additions are lost. The solutions:
synchronized void inc() { count++; } // only one thread inside the method at a time
AtomicInteger count = new AtomicInteger(); // an atomic processor operation
count.incrementAndGet();
In practice threads are rarely created by hand — there are pools: ExecutorService pool = Executors.newFixedThreadPool(4);
pool.submit(task) returns a Future with the result.
The order in which threads print is undefined — that's why we print after join().
Task. Calculate the sum 1 + 2 + … + n in t threads: thread i sums its own part of the range
(split it however you like) and adds the result to a shared AtomicLong. Each thread also increases
a shared counter k times through a synchronized method. Print the sum and the counter (it must be exactly t·k).
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.