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

package 课上;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class AARunnable implements Runnable
{
    List  v = new ArrayList<>() ;
    Random a = new Random();

    @Override
    public void run()
    {
        for(int i = 1;i<11;i++)
        {
            System.out.println(""+i+"次,去"+Thread.currentThread().getName()+"");
            
            if(i==10)
            {
                System.out.println("最后决定去"+Thread.currentThread().getName());
                System.exit(0);
            
            }
            
            try {
                Thread.sleep(a.nextInt(1000));
            } catch (InterruptedException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
        }    
            
            
    }
    
}
package 课上;

public class CEshiAA {

    public static void main(String[] args) 
    {
        AARunnable  a = new AARunnable() ;
        
        Thread  td1 = new Thread(a, "淄博") ;
    
        td1.start();
        
        Thread  td2 = new Thread(a, "济南") ;
        
        td2.start();
        
        
        
    }

}

package 课上;

import java.util.Random;

public class AAAAAAAA {

    public static void main(String[] args) {
        Thread t1 = new Thread( ) ;
        
        Demo1 d1 = new Demo1("淄博") ;
                
        Demo1 d2 = new Demo1("济南") ;
        
        d1.start();//开启线程,调用run 方法
        
        d2.start();
    }

}


class Demo1 extends Thread
{
    private String name ;
    Random a = new Random();
    
    Demo1( String name )
    {
        this.name = name ;
    }
    
    public void run( ) 
    {
        for( int i = 1 ; i < 11 ; i++ )
        {
            System.out.println(""+i+"次,去"+name+"");
            
            if(i==10)
            {
                System.out.println("最后决定去"+name +"");
                
                System.exit(0); 
            }
            try {
                Thread.sleep(a.nextInt(1000));
            } catch (InterruptedException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
        }
    }
    
}

原文地址:https://www.cnblogs.com/20gg-com/p/5919592.html