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.1. Thread Class
Import java.util.*;p ublic class City extends Thread {@Overridepublic void run () {test ();} public void Test () {//random number randomly out of sleep time random a = new random (); for (int i = 0; i < i++) {int b = a.nextint (1000); System.out.println (This.getname ());//System.out.println (b); try {thread.sleep (b);} catch (Interruptedexception e) { E.printstacktrace ();} When a thread outputs to a 10th, it gets the city to go and ends directly if (i = = 9) {System.out.println ("I Want to go" + this.getname ()); System.exit (0);}} public static void Main (string[] args) {City city1 = new City (); City1.setname ("Zibo"); City1.start (); City City2 = new City (); City2.setname ("Jinan"); City2.start ();}
Run results
2. Runnable interface
Import java.util.*;p Ublic class City2 implements Runnable {@Override public void run () {//random number of random sleep time Random a=new random (); for (int i = 0; i < i++) {int b=a.nextint (1000); System.out.println (Thread.CurrentThread (). GetName ()); System.out.println (b); try {thread.sleep (b); } catch (Interruptedexception e) { TODO Auto-generated catch block E.printstacktrace (); }//When a thread outputs to the 10th, it gets to the city and ends directly if (i==9) { SYSTEM.OUT.PRINTLN ("I Want to Go" +thread.currentthread (). GetName ()); System.eXIT (0); }}} public static void Main (string[] args) {City city1=new city (); City1.setname ("Jinan"); City1.start (); City City2=new City (); City2.setname ("Zibo"); City2.start (); } }
Run results
Java multithreading practice go to that city