zoukankan      html  css  js  c++  java
  • java 线程练习题1

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

    package com.hanqi.xiancheng;
    
    import java.util.Random;
    
    public class Test6 implements Runnable {
    
        Random r = new Random();
        int a = r.nextInt(1000);
    
        @Override
        public void run() {
    
            for (int i = 0; i < 10; i++)
    
            {
                System.out.println(Thread.currentThread().getName());
    
                try {
                    Thread.sleep(a);
                } catch (InterruptedException e) {
                    // TODO 自动生成的 catch 块
                    e.printStackTrace();
                }
            }
    
        }
    
    }
    package com.hanqi.xiancheng;
    
    import java.util.Random;
    
    public class Test8 extends Thread {
    
        Random r = new Random();
        int a = r.nextInt(1000);
    
        @Override
        public void run() {
    
            for (int i = 0; i < 10; i++)
    
            {
                System.out.println(Thread.currentThread().getName());
    
                try {
                    Thread.sleep(a);
                } catch (InterruptedException e) {
                    // TODO 自动生成的 catch 块
                    e.printStackTrace();
                }
            }
        }
    
    }
    package com.hanqi.xiancheng;
    
    public class Test7 {
    
        public static void main(String[] args) {
            // TODO 自动生成的方法存根
            Thread th=new Thread(new Test6());
            th.setName("海南");
            th.start();
            Thread th2=new Thread(new Test6());
            th2.setName("西藏");
            th2.start();
    
        }
        
    
    }

    package com.hanqi.xiancheng;
    
    public class Test7 {
    
        public static void main(String[] args) {
            // TODO 自动生成的方法存根
    
            Test8 th3=new Test8();
            th3.setName("海南");
            th3.start();
            Test8 th4=new Test8();
            th4.setName("西藏");
            th4.start();
        }
        
    
    }

  • 相关阅读:
    按不同国家语言进行字符串排序
    ASP.net的客户端脚本
    MSN photo upload tool
    Cool SMIL
    asp.net 2.0 中无刷新机制
    EF Code First 学习笔记:约定配置
    EF Code First学习笔记 初识Code First
    Silverlight、XAML实现滚动文字
    使用Nlog记录日志到数据库
    WCF:如何将net.tcp协议寄宿到IIS
  • 原文地址:https://www.cnblogs.com/jskbk/p/5557482.html
Copyright © 2011-2022 走看看