随便选择两个城市作为预选旅游目标。实现两个独立的线程分别显示10次城市名,每次显示后休眠一段随机时间(1000ms以内),哪个先显示完毕,就决定去哪个城市。分别用Runnable接口和Thread类实现。
package com.hanqi.xiancheng; import java.util.Random; public class Test6 implements Runnable { Random r = new Random(); int a = r.nextInt(1000); @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName()); try { Thread.sleep(a); } catch (InterruptedException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } } }
package com.hanqi.xiancheng; import java.util.Random; public class Test8 extends Thread { Random r = new Random(); int a = r.nextInt(1000); @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName()); try { Thread.sleep(a); } catch (InterruptedException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } } }
package com.hanqi.xiancheng; public class Test7 { public static void main(String[] args) { // TODO 自动生成的方法存根 Thread th=new Thread(new Test6()); th.setName("海南"); th.start(); Thread th2=new Thread(new Test6()); th2.setName("西藏"); th2.start(); } }
package com.hanqi.xiancheng; public class Test7 { public static void main(String[] args) { // TODO 自动生成的方法存根 Test8 th3=new Test8(); th3.setName("海南"); th3.start(); Test8 th4=new Test8(); th4.setName("西藏"); th4.start(); } }
时间: 2024-10-12 20:48:55