1.随便选择两个城市作为预选旅游目标。实现两个独立的线程分别显示10次城市名,每次显示后休眠一段随机时间(1000ms以内),哪个先显示完毕,就决定去哪个城市。分别用Runnable接口和Thread类实现。
稍改,如下: public class Testcity{ public static void main(String args[]){ City1 thread1=new City1("上海"); City2 c2=new City2("福州"); Thread thread2=new Thread(c2); thread1.start(); thread2.start(); } } class City1 extends Thread{ private String name; //构造方法 public City1(String name){ this.name=name; } public void run(){//线程的run方法 int i=1; while(i<11){ System.out.println("这是我第"+i+"次想去"+name); try{ Thread.sleep((int)(Math.random()*1000)); }catch(Exception e){} i++; } System.out.println("我决定去"+name); System.exit(0); } } class City2 implements Runnable{ private String name; //构造方法 public City2(String name){ this.name=name; } public void run(){ int i=1; while(i<11){ System.out.println("这是我第"+i+"次想去"+name); try{ Thread.sleep((int)(Math.random()*1000)); }catch(Exception e){} i++; } System.out.println("我决定去"+name); System.exit(0); } }
思考题:实现在分线程调用主线程的join(), 让主线程先执行完毕,分线程再继续执行。(有待完善)
java里面在主线程产生多个子线程,怎么让这些子线程同时运行,运行完以后再继续执行主线程??
public class ThreadTest { static int i=0; public static void main(String[]args){ //建立3个子线程,以i,i,n,m作为子线程是否结束的判断 //当所有子线程运行完才开始主线程 System.out.println("主线程开始"); Thread t1=new Thread(){ public void run(){ System.out.println("子线程1"); ThreadTest.i+=1; } }; //开启线程1 t1.start(); Thread t2=new Thread(){ public void run(){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("子线程2"); ThreadTest.i+=1; } }; //开启线程2 t2.start(); Thread t3=new Thread(){ public void run(){ System.out.println("子线程3"); ThreadTest.i+=1; } }; //开启线程3 t3.start(); boolean res=true; while(res){ //这里判断子线程是否运行完了 if(ThreadTest.i==3){ System.out.println("主线程结束"); res=false; } } } }