Back
Close

Computing with Data

elgeish
31.4K views

Deadlocks - Part II

import java.util.concurrent.atomic.AtomicInteger;
class DeepThoughtTask implements Runnable {
static AtomicInteger finalResult = new AtomicInteger(0);
private int computeResult() {
return 1; // assume this is a long-running task
}
public void run() {
// This is lock-free on modern CPUs
finalResult.addAndGet(computeResult());
}
}
public class Main {
public static void main(String args[]) throws Exception {
DeepThoughtTask task = new DeepThoughtTask();
Thread[] threads = new Thread[42];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(task);
threads[i].start(); // fork; non-blocking
}
for (int i = 0; i < threads.length; i++) {
threads[i].join(); // wait; blocking
}
System.out.println("answer: " + DeepThoughtTask.finalResult);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants