Command Palette

Search for a command to run...

Back to the lesson: Topic 13.1 — Threads and Runnable
Core Java · Example 1 of 4

Split a sum across three threads

The workers may finish in any order, but main prints only after joining all of them, so the output never changes.

A thread is an independent path of execution inside one program, with its own call stack but sharing the same heap. You describe the work as a Runnable and run it on a new Thread with start(); the JVM maps each such platform thread to an operating system thread.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Start four threads that each count the even numbers in a quarter of 1..4000 into their own array slot. Join them and print each count and the total.

02

Create a thread named printer whose task stores its own name and whether it is a daemon into a String[]. Start it, join it and print the stored values.

03

Write a thread whose task throws ArithmeticException (divide by zero). Install an uncaught exception handler that prints the exception class name, and print done after joining.

Explain it without notes

01

What is the difference between a process and a thread, and what do threads in the same JVM share?

02

Why does calling run() instead of start() not create concurrency?

03

Why can a lambda passed to a thread only use effectively final local variables?

04

What decides when the JVM exits, and what are daemon threads for?

Split a sum across three threads
Sign in to run this example in your browser.

Expected output

main runs on: main
worker-0 summed 1..1000 = 500500
worker-1 summed 1001..2000 = 1500500
worker-2 summed 2001..3000 = 2500500
total 1..3000 = 4501500
formula n(n+1)/2 = 4501500