Threading issues-how one thread pulls out the result of another thread.

Source: Internet
Author: User
Tags thread class

Problem: Two threads are built, thread 1 is computed 1*1+~+99*99, thread 2 prints the outgoing thread 1 name, and reads the calculation results of threads 1 at intervals?

1  Public classother{2      Public Static volatile intsum;3      Public Static voidMain (string[] args) {4Thread t1=NewThreadClass ();5T1.setname ("I am thread 1");6Thread t2=NewThread (NewRunnableclass (T1.getname ()));7T2.setdaemon (true);8 T1.start ();9 T2.start ();Ten     } One     Static classRunnableclassImplementsrunnable{ A     PrivateString name; -      PublicRunnableclass (String name) { -          This. name=name; the     } -      Public voidrun () { -          while(true){ -                  +                 Try{ -System.out.println (name+ "" +sum); +Thread.Sleep (3000); A}Catch(Exception e) { at System.out.println (e); -             } -         } -     } -      - } in Static classThreadClassextendsThread { -      Public voidrun () { to          for(intk=1;k<100;k++){ +             Try{sum+=count (k); -Sleep (1000);}Catch(Exception e) { the System.out.println (e); *             } $         }Panax Notoginseng     } -      Public intCountinti) { the         return(i*i); +         } A      the } +}

The runnable interface does not have a method inside the Thread class, so when you use the Sleep method, you need to Thread.Sleep (); Remember that the Sleep method returns an exception, so use try to do the exception handling. The effect of static! Remember, next time will be written, please give more suggestions, thank you!

Threading issues-how one thread pulls out the result of another thread.

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.