그래서 이것을 구현할 수있는 한 가지 방법은 1 명의 경쟁자에게 2 개의 개별 스레드를 사용하는 것입니다. 기능을 실행하는 ThreadTimer과 ThreadHelper
public class ThreadTimer extends Thread {
public ThreadTimer() {
}
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(ThreadTimer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
그리고 ThreadHelper
public class ThreadHelper extends Thread {
Calculator c;
public ThreadHelper(Calculator c) {
this.c = c;
}
public Calculator getC() {
return c;
}
public void setC(Calculator c) {
this.c = c;
}
@Override
public void run() {
long startTime = System.nanoTime();
long plus = c.add();
long endTime = System.nanoTime();
long duration = (endTime - startTime);
long seconds = duration/1000000000;
System.out.println("Add Time: " + seconds);
}
}
당신이 내 코드에서 계산기를 호출하고 만들어 귀하의 인터페이스를 제공합니다.
이것은 add가 소요 시간을 출력하고 출력하는 시간을 계산합니다. 나는 계산은 훨씬 더 복잡 확신하지만, 질문에 대한 잠재적 인 대답은 시작 클래스에 와서 : ThreadTimer 전에 완료하면 당신은 더 이상 stop()
방법을 사용할 수 없기 때문에, 당신은 예외를 던질 수
public class Competition {
public static void main(String[] args) throws InterruptedException, Exception {
Calculator jim = new JimSmithsCalculator();
Calculator john = new JohnDoesCalculator();
ThreadHelper jimsThread = new ThreadHelper(jim);
ThreadTimer time1 = new ThreadTimer();
ThreadHelper JohnsThread = new ThreadHelper(john);
ThreadTimer time2 = new ThreadTimer();
time1.start();
jimsThread.start();
//This will run a loop ensuring both of the above threads are terminated...
checkSeconds(time1, jimsThread);//This also does the time check
//...Before moving on to these threads.
time2.start();
JohnsThread.start();
checkSeconds(time2, JohnsThread);
}
public static void checkSeconds(ThreadTimer time, ThreadHelper t) throws Exception {
while (t.isAlive()) {
if (time.getState() == Thread.State.TERMINATED) {
throw new Exception(t.getName() + " >> " + t.getClass() + " Failed!!!");
}
}
}
}
ThreadHelper는 않습니다.
이렇게하면 예외가 출력되고 프로그램이 계속됩니다. 그런 다음 경쟁 업체 스레드가 예외로 인해 실패했음을 알 수 있습니다.
public static void checkSeconds(ThreadTimer time, ThreadHelper t) throws Exception {
while (t.isAlive()) {
if (time.getState() == Thread.State.TERMINATED) {
throw new Exception(t.getName() + " >> " + t.getClass() + " Failed!!!");
}
}
}
당신이 원하는 것처럼이 정확하게 작동한다면 나도 몰라 :
이 임의의 코드를 귀하의 질문에 대한 내 대답의 모든 주요 점은이 방법이다.
적어도이 아이디어가 나올 수 있기를 바랍니다.
별도의 프로세스로 실행하십시오. 그 과정을 끝내라. –