This is an example that shows how to use the Join () method.
Problem:
Computes the value of an expression 1*2/(1+2) using Java multithreading.
Solution:
Use one thread to do the addition, the other to do the multiplication, and the main thread to do the division. Because there is no need for communication between threads, we only need to consider the order in which threads are executed.
In the main thread, we let the addition and multiplication threads join to the main thread, and the join () method is for the main method to wait until the thread that called the join finishes executing. In this example, we want the addition and multiplication lines to end enters upgradeable and then calculate the division operation.
PackageSimplejava;classAddextendsThread {intvalue; Public voidrun () {value= 1 + 2; }}classMulextendsThread {intvalue; Public voidrun () {value= 1 * 2; }} Public classQ22 { Public Static voidMain (string[] args) {Add T1=NewAdd (); Mul T2=NewMul (); T1.start (); T2.start (); Try{t1.join (); T2.join (); } Catch(interruptedexception e) {e.printstacktrace (); } Doublen = ((Double) T2.value/t1.value); SYSTEM.OUT.PRINTLN (n); }}
Link: http://www.programcreek.com/2012/08/interview-question-use-java-thread-to-do-math-calculation/
Simple Java interview problem-using Java threads to do mathematical operations