标签:
随便选择两个城市作为预选旅游目标。实现两个独立的线程分别显示10次城市名,
每次显示后休眠一段随机时间(1000ms以内),哪个先显示完毕,就决定去哪个城市。
分别用Runnable接口和Thread类实现。
package com.xiancheng; import java.util.Random; public class Test6 extends Thread { @Override public void run() { test(); } public void test() { for(int i=1;i<=10;i++) { Random r=new Random(); int n=r.nextInt(1000); try { Thread.sleep(n); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("我第"+i+"次想去:"+Thread.currentThread().getName()); if(i==10) { System.out.println("我决定去:"+Thread.currentThread().getName()); System.exit(0); } } } public static void main(String[] args) { Test6 t1=new Test6(); t1.setName("北京"); t1.start(); Test6 t2=new Test6(); t2.setName("上海"); t2.start(); } }
package com.xiancheng; import java.util.Random; public class Test7 implements Runnable { @Override public void run() { for(int i=1;i<=10;i++) { Random r=new Random(); int n=r.nextInt(1000); try { Thread.sleep(n); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("我第"+i+"次想去:"+Thread.currentThread().getName()); if(i==10) { System.out.println("要去的是:"+Thread.currentThread().getName()); System.exit(0); } } } public static void main(String[] args) { Thread th=new Thread(new Test7()); th.setName("北京"); Thread th1=new Thread(new Test7()); th1.setName("上海"); th.start(); th1.start(); } }
标签:
原文地址:http://www.cnblogs.com/wallan/p/5557847.html