Interview Question – Use Java Thread to Do Math Calculation

This is an example for showing how to use join(). Interview question: Use Java multi-threading to calculate the expression 1*2/(1+2).


Use one thread to do addition, one thread to do multiplication, and a main thread to do the division. Since there is no need to communicate data between threads, so only need to consider the order of thread execution.

In the main thread, let addition and multiplication join the main thread. The join() method is used when we want the parent thread waits until the threads which call join() ends. In this case, we want addition and multiplication complete first and then do the division.

class Add extends Thread {
	int value;
	public void run() {
		value = 1 + 2;
class Mul extends Thread {
	int value;
	public void run() {
		value = 1 * 2;
public class Main{
	public static void main(String[] args){
		Add t1 = new Add();
		Mul t2 = new Mul();
		try {
		} catch (InterruptedException e) {
		double n = ((double)t2.value/t1.value);
Category >> Concurrency  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";
  • Stephanie Riggs

    many thanks for sharing..was doing a similar thing but got stuck..luckily came across your piece..everything resolved..thanks again

  • ryanlr

    Corrected. Thanks!

  • robin

    Shouldn’t this line double n = ((double)t1.value/t2.value); be double n = ((double)t2.value/t1.value); as per the expression ‘1*2/(1+2)’