Java Threading Exercises 1

Source: Internet
Author: User

Choose from two cities as a pre-selected destination. The implementation of two separate threads display 10 city names, each time after each display sleep a random time (within 1000ms), which first displayed, decided to go to which city. Implemented using the Runnable interface and the thread class, respectively.

 PackageCom.hanqi.xiancheng;ImportJava.util.Random; Public classTest6ImplementsRunnable {Random R=NewRandom (); intA = R.nextint (1000); @Override Public voidrun () { for(inti = 0; I < 10; i++) {System.out.println (Thread.CurrentThread (). GetName ()); Try{Thread.Sleep (a);}Catch(interruptedexception e) {//TODO Auto-generated catch blockE.printstacktrace (); }        }    }}
 PackageCom.hanqi.xiancheng;ImportJava.util.Random; Public classTest8extendsThread {Random R=NewRandom (); intA = R.nextint (1000); @Override Public voidrun () { for(inti = 0; I < 10; i++) {System.out.println (Thread.CurrentThread (). GetName ()); Try{Thread.Sleep (a); } Catch(interruptedexception e) {//TODO Auto-generated catch blockE.printstacktrace (); }        }    }}
 PackageCom.hanqi.xiancheng; Public classTest7 { Public Static voidMain (string[] args) {//TODO Auto-generated method stubsThread th=NewThread (NewTest6 ()); Th.setname (Hainan);        Th.start (); Thread Th2=NewThread (NewTest6 ()); Th2.setname (Tibet);    Th2.start (); }    }

 Package Com.hanqi.xiancheng;  Public class Test7 {    publicstaticvoid  main (string[] args) {        // TODO Auto-generated method stubs         Test8 th3=new  Test8 ();        Th3.setname ("Hainan");        Th3.start ();        Test8 Th4=new  Test8 ();        Th4.setname ("Tibet");        Th4.start ();    }    }

Java Threading Exercises 1

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.