2. 继承Thread类
public class RandCity {
//入口
public static void main(String args[]) throws Exception{
//循环十次
for(int i=0;i<10;i++){
//启动城市1 线程
//创建城市1 实例
City1 c1 = new City1();
c1.start();
//得到1000 以内的随机休眠时间
Random rand = new Random();
long time1= rand.nextInt(1000);
//休眠一次
c1.sleep(time1);
City2 c2= new City2();
c2.start();
Random rand1 = new Random();
long time2= rand1.nextInt(1000);
c2.sleep(time2);
}
}
}
class City1 extends Thread{
public void run(){
System.out.println("city one");
}
}
class City2 extends Thread{
public void run(){
System.out.println("city two");
}
}
程序是不需要每句都进行注释的,只要你认真看应该能看的懂
实现Runnable 接口
public class RandCity {
//入口
public static void main(String args[]) throws Exception{
//循环十次
for(int i=0;i<10;i++){
//启动城市1 线程
//创建城市1 实例
Thread t = new Thread(new City1());
// City1 c1 = new City1();
t.start();
//得到1000 以内的随机休眠时间
Random rand = new Random();
long time1= rand.nextInt(1000);
//休眠一次
t.sleep(time1);
City2 c2= new City2();
Thread t1 = new Thread(c2);
t1.start();
Random rand1 = new Random();
long time2= rand1.nextInt(1000);
t1.sleep(time2);
}
}
}
class City1 implements Runnable{
public void run(){
System.out.println("city one");
}
}
class City2 implements Runnable{
public void run(){
System.out.println("city two");
}
}