1. 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.
ImportJava.util.Random;//Multithreaded Classes//1. Is a subclass of thread//2. Overriding the Run method Public classTest01extendsthread{@Override Public voidrun () { for(inti=0;i<10;i++) {System.out.println (Thread.CurrentThread (). GetName ()); Random ran=NewRandom (); intA1=ran.nextint (1000); Try{thread.sleep (A1); } Catch(interruptedexception e) {//TODO Auto-generated catch blockE.printstacktrace (); } } } }
Public class Test02 { publicstaticvoid main (string[] args) { new Test01 (); T1.setname ("Chongqing"); T1.start (); New Test01 (); T2.setname ("Sichuan"); T2.start (); }}
ImportJava.util.Random; Public classTest03ImplementsRunnable {@Override Public voidrun () {//TODO Auto-generated method stubs for(inti=0;i<10;i++) {System.out.println (Thread.CurrentThread (). GetName ()); Random ran=NewRandom (); intA1=ran.nextint (1000); Try{thread.sleep (A1); } Catch(interruptedexception e) {//TODO Auto-generated catch blockE.printstacktrace (); } } }}
Importcom.hanqi.test.Test03; Public classTest04 { Public Static voidMain (string[] args) {//multithreading for starting interface mode//cannot be started directlyTest03 t3 =NewTest03 (); //you need to construct thread to give him an instance of the Runnable implementation class.Thread td =NewThread (T3); //Modify the name of a threadTd.setname ("Sichuan"); //Start ThreadTd.start (); Thread TD1=NewThread (T3); Td1.setname (Chongqing); Td1.start (); }}
Java Basics-Multithreading Basics Exercises