随便选择两个城市作为预选旅游目标。实现两个独立的线程分别显示10次城市名,每次显示后休眠一段随机时间(1000ms以内),哪个先显示完毕,就决定去哪个城市。分别用Runnable接口和Thread类实现。
1 import java.util.*; 2 3 public class Ly_Runnable implements Runnable { 4 public void run() { 5 test(); 6 } 7 8 public void test() { 9 Random r = new Random(); 10 try { 11 for (int i = 1; i <= 10; i++) { 12 int a = r.nextInt(1000); 13 Thread.sleep(a); 14 System.out.print(a + "秒后去"); 15 System.out.println(Thread.currentThread().getName()); 16 } 17 } catch (Exception e) { 18 e.printStackTrace(); 19 } 20 } 21 22 public static void main(String[] args) { 23 Thread tr1 = new Thread(new Ly_Runnable()); 24 tr1.setName("淄博"); 25 tr1.start(); 26 27 Thread tr2 = new Thread(new Ly_Runnable()); 28 tr2.setName("青岛"); 29 tr2.start(); 30 } 31 }
运行:
时间: 2024-10-11 17:24:18