プロジェクトで作業していて、プログラムを停止するのが難しかったです。タイマーではなくスレッドを使用しています。なぜなら、作業が簡単だったからです。基本的には、私が今問題にしているのは、main関数から静的関数への時間です。どんな助けもありがとう。私の質問がはっきりしない場合は、コードの重要な部分をコメントに含めました。 TIA静的クラスのスレッドを使用して停止条件を実装する方法
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class InLineCustomers {
@SuppressWarnings("static-access")
public static void main (String args[]){
try{
final long NANOSEC_PER_SEC = 1000l*1000*1000;
long startTime = System.nanoTime();
long time = (System.nanoTime()-startTime);
final long genTime=3*60*NANOSEC_PER_SEC;
while (time<genTime){ //Program runs for 3 minutes
customerGenerator();
Random r = new Random();
int timeValue=r.nextInt(10);
Thread.currentThread().sleep(timeValue * 1000);
}
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void customerGenerator(){
...code here
if(selection.equalsIgnoreCase("C")){
/**This doesn't working because the customerGenerator is in it's own static class
* Would the program be more difficult to read if I had everything in the main method?
* That's what I'm trying to avoid
*
* time=genTime;
JOptionPane.showMessageDialog(null,"The restaurant is no longer accepting any customers.");
*/
stop(); //This isn't working because it created a different timer
}
}
public static void stop(){
final long NANOSEC_PER_SEC = 1000l*1000*1000;
long startTime = System.nanoTime();
long time = (System.nanoTime()-startTime);
final long genTime=3*60*NANOSEC_PER_SEC;
time=genTime;
JOptionPane.showMessageDialog(null,"The restaurant is no longer accepting any customers.");
}
}
あなたはどこでもスレッドを作成しているわけではなく、単にメインスレッドを使用しています。ここには「メインクラス」または「静的クラス」はなく、静的メイン関数と静的customerGenerator関数は同じクラスに属しています。いくつかの基本的なスレッディングの概念以上に欠けているようです。 – Tibrogargan
ありがとうございましたが、私の質問には全く答えられませんでした。私は質問を編集します。 – DontPrayForMe