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).

Solution:

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();
 
		t1.start();
		t2.start();
 
		try {
			t1.join();
			t2.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
 
		double n = ((double)t2.value/t1.value);
 
		System.out.println(n);		
	}
}

3 thoughts on “Interview Question – Use Java Thread to Do Math Calculation”

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

  2. 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)’

Leave a Comment