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