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

接口Runnable:

package com.xiancheng;

import java.util.Random;

public class Lvyou2 implements Runnable {

    @Override
    public void run()
    {
        Random ra=new Random();
        int ra1=ra.nextInt(1000);
        for(int i=0;i<10;i++)
        {
            System.out.println("旅游的城市是: "+Thread.currentThread().getName());
        }
        System.out.println(Thread.currentThread().getName()+"显示完毕,");
        
        try {
            Thread.sleep(ra1);
        } catch (InterruptedException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
}
}

继承Thread:

package com.xiancheng;

import java.util.Random;

public class lvyou1 extends Thread {
    
    @Override
    public void run()
    {
        Random ra=new Random();
        int ra1=ra.nextInt(1000);
        for(int i=0;i<10;i++)
        {
            
            System.out.println("旅游的城市是: "+Thread.currentThread().getName());
        }
        System.out.println(Thread.currentThread().getName()+"显示完毕");
        
        try {
            Thread.sleep(ra1);
        } catch (InterruptedException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
    }
    

}

结果:

 

多线程练习

 

相关文章:

  • 2021-07-07
  • 2022-12-23
  • 2022-12-23
  • 2021-05-09
  • 2022-03-05
  • 2022-02-17
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-08-06
  • 2021-04-27
  • 2021-05-16
  • 2021-11-24
  • 2022-12-23
  • 2021-07-07
相关资源
相似解决方案