直接上代码:
package com.kevin.thread;
import java.util.concurrent.CyclicBarrier;
public class ThreadTime {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
CyclicBarrier cb = new CyclicBarrier(2, new TimeCalculator(startTime));
SubThread thread1 = new SubThread("Thread 1", cb);
thread1.start();
SubThread thread2 = new SubThread("Thread 2", cb);
thread2.start();
}
}
class TimeCalculator extends Thread {
private long startTime;
public TimeCalculator(long startTime) {
this.startTime = startTime;
}
public void run() {
long endTime = System.currentTimeMillis();
System.out.println("Total time cost: " + (endTime - startTime)/1000 + " s.");
}
}
class SubThread extends Thread {
private String name;
private CyclicBarrier cb;
public SubThread(String name, CyclicBarrier cb) {
super(name);
this.name = name;
this.cb = cb;
}
public void run() {
System.out.println(name + " is starting...");
try {
Thread.sleep(5000);
System.out.println(name + " is stoping...");
cb.await();
} catch (Exception e) {
e.printStackTrace();
}
}
}