zoukankan      html  css  js  c++  java
  • 多线程编程

     

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

    稍改,如下:
    
    public class Testcity{
     public static void main(String args[]){
     City1 thread1=new City1("上海");
    
      City2 c2=new City2("福州");
      Thread thread2=new Thread(c2);
      
      thread1.start();
      thread2.start();
      }
     }
     
     class City1 extends Thread{
      private String name;
      
      //构造方法
      public City1(String name){
       this.name=name;
      }
      
      public void run(){//线程的run方法
      int i=1;
      while(i<11){
       System.out.println("这是我第"+i+"次想去"+name);
    try{
        Thread.sleep((int)(Math.random()*1000));
        }catch(Exception e){}
          i++;
       }
       System.out.println("我决定去"+name);
       System.exit(0);
      }
      }
     
     class City2 implements Runnable{
      private String name;
      
      //构造方法
      public City2(String name){
       this.name=name;
       }
      public void run(){
       int i=1;
      while(i<11){
          System.out.println("这是我第"+i+"次想去"+name);
    try{
        Thread.sleep((int)(Math.random()*1000));
       }catch(Exception e){}
       i++;
       }
       System.out.println("我决定去"+name);
       System.exit(0);
      }
      }

    思考题:实现在分线程调用主线程的join(), 让主线程先执行完毕,分线程再继续执行。(有待完善)

    java里面在主线程产生多个子线程,怎么让这些子线程同时运行,运行完以后再继续执行主线程??
     
     
  • 相关阅读:
    RUNOOB.COM-python网络编程-(python3.5.0)
    windows查看服务
    计算机网络里的一些理解
    如果面试有傻逼问道oracle怎么启动的
    推荐一个学习数据库的地方
    电脑中的驱动程序是什么,是干什么的
    Raspberry Pi 4B 之 Python开发
    Ubuntu20.04+EdgexFoundry边缘计算微服务搭建-----遇到的问题-----make build 被墙问题
    Raspberry Pi 4B + Ubuntu 20.04 server for arm64 的wifi配置
    关于PicoNeo开发环境的Unity3D+AndroidSDK配置
  • 原文地址:https://www.cnblogs.com/hanruyue/p/5916820.html
Copyright © 2011-2022 走看看