• 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

  • 相关阅读:
    打印空格
    进程间的通信
    堆排序算法
    大小端的判断
    bash help
    [Android] How to disable the screen orientation?
    图片的静态动态显示效果
    WPF Threads: Build More Responsive Apps With The Dispatcher
    用node.js+express自建网站发布静态网页
    利用Apache mod_expires 与 mod_headers 实现文件缓存及mod_deflate压缩输出
  • 原文地址:https://www.cnblogs.com/homie/p/9438003.html
Copyright © 2020-2023  润新知