Simple Java interview problem-using Java threads to do mathematical operations

Source: Internet
Author: User
Tags mul

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.