Java Threading Practice Select City

Source: Internet
Author: User

Choose from two cities as a pre-selected destination. Implement two separate threads to display 10 city names, respectively,
After each display, sleep for a random time (within 1000ms), whichever is displayed first, decide which city to go to.
Implemented using the Runnable interface and the thread class, respectively.

 PackageCom.xiancheng;ImportJava.util.Random; Public classTest6extendsThread {@Override Public voidRun () {test (); }     Public voidTest () { for(inti=1;i<=10;i++) {Random R=NewRandom (); intN=r.nextint (1000); Try{thread.sleep (n); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("I first" +i+ "Want to go:" +Thread.CurrentThread (). GetName ()); if(i==10) {System.out.println ("I decided to go:" +Thread.CurrentThread (). GetName ()); System.exit (0); }                    }    }     Public Static voidMain (string[] args) {Test6 T1=NewTest6 (); T1.setname (Beijing);        T1.start (); TEST6 T2=NewTest6 (); T2.setname (Shanghai);                    T2.start (); }    }
 PackageCom.xiancheng;ImportJava.util.Random; Public classTest7ImplementsRunnable {@Override Public voidrun () { for(inti=1;i<=10;i++) {Random R=NewRandom (); intN=r.nextint (1000); Try{thread.sleep (n); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("I first" +i+ "Want to go:" +Thread.CurrentThread (). GetName ()); if(i==10) {System.out.println ("To Go is:" +Thread.CurrentThread (). GetName ()); System.exit (0); }        }            }     Public Static voidMain (string[] args) {Thread th=NewThread (NewTest7 ()); Th.setname (Beijing); Thread Th1=NewThread (NewTest7 ()); Th1.setname (Shanghai);        Th.start ();    Th1.start (); }}

Java Threading Practice Select City

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.