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

posted @ 2018-08-07 16:55  mingtao  阅读(123)  评论(0编辑  收藏  举报