public class Testlvyou extends Thread{
@Override
public void run() {
test();
}
private void test()
{
//用随机数随即一个休眠时间
Random r=new Random();
int b1=r.nextInt(1000);
for(int i=0;i<10;i++)
{
System.out.println(this.getName());
try {
Thread.sleep(b1);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
if(i==9)//当随即到最后一个时结束,输出想要去的城市
{
System.out.println("我要去的城市是:"+this.getName());
break;
}
}
}
}
package zuoye;
public class LvyouTest {
public static void main(String[] args) {
Testlvyou t1=new Testlvyou();
t1.setName("上海");
t1.start();
Testlvyou t2=new Testlvyou();
t2.setName("北京");
t2.start();
}
}
package zuoye;
import java.util.Random;
public class Testlvyou implements Runnable {
@Override
public void run() {
test();
}
private void test() {
//用随机数随即一个随机时间
Random r=new Random();
for(int i=0;i<10;i++)
{
int b=r.nextInt(1000);
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(b);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
if(i==9)
{
System.out.println("我要去的城市是:"+Thread.currentThread().getName());
break;
}
}
}
}
package zuoye;
public class LvyouTest {
public static void main(String[] args) {
Testlvyou tl=new Testlvyou();
Thread t1=new Thread(tl, "北京");
t1.start();
Thread t2=new Thread(tl, "上海");
t2.start();
}
}
![]()