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


    //继承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();
    
    }
    

    }

  • 相关阅读:
    Ubuntu 11.10 安装JDK
    virtualbox下安装ubuntu
    GridView控件的DataKeyNames
    Asp.net中防止用户多次登录的方法
    在asp.net中使用线程
    SQL2008更改表结构问题
    Ubuntu安装run文件
    ContextSwitchDeadlock
    CheckedListBox用法
    C#图片加水印图片和文字
  • 原文地址:https://www.cnblogs.com/nicebaby/p/5917741.html
Copyright © 2020-2023  润新知