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

  • 相关阅读:
    Python函数
    Python的集合框架
    go的相关用法
    如何完整反编译AndroidMainfest.xml
    英语中时间的表达方法
    3. vue脚手架安装 express 框架使用 vue框架 weiUI
    2. TypeScript笔记
    基于SignalR的消息推送与二维码描登录实现
    MVC-Model数据注解(三)-Remote验证的一个注意事项
    MVC Remote属性验证
  • 原文地址:https://www.cnblogs.com/jskbk/p/5557482.html
Copyright © 2011-2022 走看看