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

  • 相关阅读:
    基于发布/订阅模型的应用程序的主循环设计
    C++使用继承时子对象的内存布局
    安装 CentOS 后的系统配置及软件安装备忘
    环形无锁队列
    并发编程基础
    线程池实现
    Git远程操作
    Unix权限管理
    jquery中,某些写法后来更新导致版本不支持的替代方法
    js相关
  • 原文地址:https://www.cnblogs.com/homie/p/9438003.html
Copyright © 2011-2022 走看看