Java多线程练习去那个城市

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

public class City extends Thread {

	@Override
	public void run() {

		test();
	}

	public void test() {
		// 随机数 随机出休眠时间
		Random a = new Random();

		for (int i = 0; i < 10; i++) {
			int b = a.nextInt(1000);
			System.out.println(this.getName());
			// System.out.println(b);
			try {

				Thread.sleep(b);

			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			// 当某个线程输出到第10个的时候 得到要去的城市 并直接结束
			if (i == 9) {
				System.out.println("我想去" + this.getName());
				System.exit(0);
			}
		}

	}

	public static void main(String[] args) {

		City city1 = new City();
		city1.setName("淄博");
		city1.start();

		City city2 = new City();
		city2.setName("济南");
		city2.start();

	}

}

  

运行结果

2、Runnable接口

import java.util.*;
public class City2 implements Runnable {

	 @Override
	    public void run() {
	        //随机数  随机出休眠时间
	                Random a=new Random();        
	                        
	                for (int i = 0; i < 10; i++) 
	                { 
	                    int b=a.nextInt(1000);            
	                    System.out.println(Thread.currentThread().getName());
	                    //System.out.println(b);
	                    try 
	                    {
	                        
	                        Thread.sleep(b);
	                        
	                        
	                    } 
	                    catch (InterruptedException e) 
	                    {
	                        // TODO 自动生成的 catch 块
	                        e.printStackTrace();
	                    }
	                    //当某个线程输出到第10个的时候    得到要去的城市 并直接结束
	                    if(i==9)
	                    {
	                        System.out.println("我想去"+Thread.currentThread().getName());
	                        System.exit(0);
	                    }
	                }

	    }    
	        public static void main(String[] args) {
	        
	        
	        City city1=new City();
	        city1.setName("济南");      
	        city1.start();
	    
	        
	        City city2=new City();
	        city2.setName("淄博");       
	        city2.start();
	    
	            
	        }   

}

  

运行结果

原文地址:https://www.cnblogs.com/mutougezi/p/5558107.html