package study;
import java.util.concurrent.TimeUnit;
public class Test {
public static class myThread extends Thread {
int sleepSeconds;
public myThread(String name,int seconds) {
this.setName(name);
this.sleepSeconds = seconds;
}
@Override
public void run() {
long startTime = System.currentTimeMillis();
System.out.println(this.getName() + "开始执行");
try {
TimeUnit.SECONDS.sleep(sleepSeconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
System.out.println(this.getName() + "结束执行,耗时:" + String.valueOf(endTime - startTime));
}
}
public static void main(String[] args) throws InterruptedException {
long start = System.currentTimeMillis();
System.out.println("------主线程开始------");
myThread t1 = new myThread("线程1", 2);
t1.start();
myThread t2 = new myThread("线程2", 5);
t2.start();
t1.join();
t2.join();
long end = System.currentTimeMillis();
System.out.println("主线程执行完毕,耗时:" + String.valueOf(end - start));
}
}
执行结果
------主线程开始------
线程1开始执行
线程2开始执行
线程1结束执行,耗时:2016
线程2结束执行,耗时:5002
主线程执行完毕,耗时:5017
可以看出,整个程序的执行时间约等于耗时最长的线程2执行的时间,在线程1睡眠时线程2执行了,只有当线程1和线程2都执行完毕后主线程才会执行