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

    主线程执行5个5秒动作,运行25秒。另外一个方法执行6个5秒动作,花费30秒。

    如果要跑完这两者,需要25+30秒。

    但是如果用java多线程。只需要max(25,30)秒

    代码如下

    public class ThreadDemo extends Thread {
    @Override
    public void run() {
    int i = 6;
    while (i > 0) {
    System.out.println(Thread.currentThread().getName() + " is running ... " + i ); // 打印当前线程的名字
    i -= 1;
    try {
    Thread.sleep(5000); // 休息1000ms
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }

    public static void main(String[] args) {

    long startTime = System.currentTimeMillis();
    ThreadDemo td = new ThreadDemo();
    td.setName("anotherThread");
    td.start();
    int n = 5;
    while(n > 0) {
    System.out.println(Thread.currentThread().getName() + " is running ... " + n); // 打印当前线程的名字
    n -= 1;
    try {
    Thread.sleep(5000); // 休息1000ms
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    System.out.println("exit 0");
    long endTime = System.currentTimeMillis();
    float excTime = endTime - startTime ;
    System.out.println("time : "+ excTime);
    }
    }

    -------------------------------------------------------------------------------------------------------------------------------可爱的分割线-----------------------------------------------------------------------------

    控制台输出结果如下:

    main is running ... 4
    anotherThread is running ... 6
    main is running ... 3
    anotherThread is running ... 5
    main is running ... 2
    anotherThread is running ... 4
    main is running ... 1
    anotherThread is running ... 3
    main is running ... 0
    anotherThread is running ... 2
    exit 0
    anotherThread is running ... 1
    time : 25005.0

  • 相关阅读:
    ArcMap+ArcCatalog手工新建点层及添加数据
    zedGraph 图表控件总结(一)
    Android 开发学习笔记(五)—— 最简单的注册界面
    repeater实现删除按钮
    repeater分页实例
    FCKeditor的使用说明
    javascript:void(0)是什么意思
    为asp.net控件点击事件添加Confirm()
    LINQ判断素数
    U盘文件不能删除,怎么处理
  • 原文地址:https://www.cnblogs.com/homie/p/9438003.html
Copyright © 2011-2022 走看看