zoukankan      html  css  js  c++  java
  • java线程实现和集合类综合问题

    package com.stringtest;

    import java.util.HashSet;
    import java.util.Set;

    public class Thread1 implements Runnable {
    public void run() {
    Set set = new HashSet();
    for (int i = 0; i < 10; i++) {
    set.add((int)(Math.random()*100));
    }
    System.out.println(set);
    System.out.println(set.size());
    }
    }
    线程实现代码
    *********************
    package com.stringtest;

    import java.util.HashSet;
    import java.util.Set;

    public class Poeal {
    public static void main(String[] var12) throws InterruptedException{
    Thread1 thread1 = new Thread1();
    for (int i=0;i<12;i++) {
    System.out.println("线程第"+i+"次启动");
    thread1.run();
    Thread.sleep(1000);
    }
    }
    }
    线程运行代码
    ***********************
    运行结果

    线程第0次启动
    [16, 32, 80, 96, 84, 85, 71, 89, 47, 95]
    10
    线程第1次启动
    [17, 33, 66, 19, 84, 53, 75, 12, 76, 62]
    10
    线程第2次启动
    [66, 50, 82, 67, 69, 88, 75, 60, 77, 15]
    10
    线程第3次启动
    [82, 50, 69, 85, 87, 61, 13, 93, 79, 31]
    10
    线程第4次启动
    [80, 65, 82, 83, 67, 5, 7, 25, 94, 79]
    10
    线程第5次启动
    [32, 4, 6, 38, 87, 56, 25, 59, 28, 46]
    10
    线程第6次启动
    [16, 64, 65, 4, 9, 25, 90, 91, 13]
    9
    线程第7次启动
    [96, 51, 53, 7, 8, 42, 10, 59, 43, 60]
    10
    线程第8次启动
    [64, 17, 81, 19, 35, 23, 12, 77, 29, 47]
    10
    线程第9次启动
    [80, 32, 33, 82, 98, 3, 69, 92, 93, 45]
    10
    线程第10次启动
    [82, 4, 21, 6, 39, 88, 9, 43, 44, 31]
    10
    线程第11次启动
    [2, 3, 83, 53, 38, 6, 24, 9, 11, 92]
    10

    Process finished with exit code 0

    问题:

    为何有一次结果,输出为9呢

  • 相关阅读:
    Markdown示例
    初识Markdown
    Ubuntu源整理
    Vi编辑器入门
    Ubuntu,Linux入门系统
    [其他]volatile 关键字
    Qt5:随窗口大小变化背景图片自动缩放的实现
    Qt5:不规则按钮的实现---通过贴图实现
    windows编程:创建DLL
    [转]Firefox拦截12306订票网站的解决办法
  • 原文地址:https://www.cnblogs.com/peters/p/8149254.html
Copyright © 2011-2022 走看看