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