だから、これを実装できる方法の1つは、競合他社に2つのスレッドを使用することです。あなたは、私は私のコードで電卓を呼び出しています作成したインターフェース
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);
}
}
関数を実行ThreadTimerとA 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。
これは、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!!!");
}
}
}
あなたがそれを望むよう、これは正確に動作するかどうかはわからない:
このランダムなコードやあなたの質問に私の答えのすべての主要なポイントは、この方法です。
私はこれが少なくともアイデアを発することを願っています。
別のプロセスで実行します。プロセスを終了します。 –