实验六 多线程编程 1.随便选择两个城市作为预选旅游目标。实现两个独立的线程分别显示10次城市名,每次显示后休眠一段随机时间(1000ms以内),哪个先显示完毕,就决定去哪个城市。分别用Runnable接口和Thread类实现。

时间:2024-01-16 09:59:50

//继承Thread类

package zuoye;

//继承Thread类

public class City extends Thread{

private String name;

public City(String name) {

super();

this.name = name;

}

public void run() {

for(int i=0;i<10;i++)

{

System.out.println(this.name+i);

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

// TODO 自动生成的 catch 块

e.printStackTrace();

}

}

}

}

//Runnable接口

package zuoye;

//Runnable接口

public class City2 implements Runnable {

@Override
public void run() {
for(int i=0;i<10;i++)
{
System.out.println(Thread.currentThread().getName()+" "+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
} }

}

//测试类

package zuoye;

public class Test {

public static void main(String[] args) {
//Thread类 City c1=new City("铁岭");
c1.start();
City c2=new City("纽约");
c2.start(); //Runnable
City2 t1=new City2();
Thread t2=new Thread(t1, "淄博");
t2.start();
Thread t3=new Thread(t1, "美国");
t3.start(); }

}