我正在开发一个项目,并且在停止该程序时遇到了一些困难。我使用的是线程而不是定时器,因为我觉得这很容易处理。基本上,我现在面临的问题是从主功能到静态功能的时间。任何帮助,将不胜感激。如果我的问题不明确,我会在代码的重要部分添加注释。 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